Attributes modify element behavior or provide metadata. They appear only on start tags (or single-tag void elements). Order among attributes does not matter to the parser—pick a team convention for readability.
Syntax varieties
- Empty attribute syntax: boolean attributes may appear without a value—presence implies true (
disabled,checked,required). - Unquoted values are legal for simple tokens but omitting quotes breaks when spaces appear—prefer double quotes.
- Single-quoted strings help when double quotes appear inside the value.
Global vs local attributes
Global attributes apply broadly: id, class, lang, dir, title, hidden, data-*, ARIA aria-*, event handler attributes, and more.
Element-specific attributes configure unique behavior—examples: href on anchors, src on media, colspan on table cells, type on inputs.
IDs and classes
idmust be unique in the document; stable IDs anchor fragments (#pricing) and tie labels to controls.classholds space-separated tokens for CSS and scripting—reuse freely.
<a class="cta btn-primary" href="/pricing" id="pricing-link">
View pricing
</a>
Quoted vs boolean attributes
<!-- Boolean: presence means true -->
<input type="text" required disabled>
<!-- Same intent, explicit empty string is discouraged for booleans -->
<input type="checkbox" checked>
Rendered (disabled + checked)
Common pitfalls
- Duplicate
idvalues break assumptions in APIs and assistive tech. - Unescaped
<or&inside attribute values need entities or alternate quoting strategies. - Relying on
titlealone for critical hints—many users never hover long enough to see tooltips.
Deeper pitfalls (production)
- Microdata duplication: duplicating identifiers or fragment targets across SPA routes confuses hydration and scrolling—document how IDs regenerate per view.
- Inline event handlers (
onclick): often blocked by CSP—preferaddEventListenerfrom bundled scripts unless you consciously manage policy. - Classes as security boundaries: never—anything in the DOM can change; authorize on the server.
Global attributes teams underuse
translate="no"for trademarks or code literals that must not machine-translate.dir/langon inline phrases for mixed RTL/LTR prose.spellcheckhints for unusually formatted fields—but never replace backend validation.
Important interview questions and answers
- Q: What is the purpose of ``?
A: It forces standards mode so browsers use modern layout/parsing behavior instead of legacy quirks mode. - Q: Why is semantic HTML important in interviews and production?
A: It improves accessibility, SEO, maintainability, and reduces ARIA/JS work by using native element behavior. - Q: What is the difference between `head` and `body`?
A: `head` stores metadata/resources for the document, while `body` contains user-visible content.
Pitfall: Duplicate id values break labels, anchors, and scripts.