HTML Elements

HTML Attributes

Master HTML attributes to add functionality, styling hooks, and accessibility features to your elements. Attributes are the key to making HTML interactive and meaningful.

What are HTML attributes?

Attributes give an element extra information or settings. They go inside the opening tag as name="value" pairs, for example <a href="https://example.com" target="_blank"> or <img src="photo.jpg" alt="Sunset">. Common global attributes that work on any element include id, class, style, title, lang, hidden and data-*.

<img src="logo.png" alt="Compileum logo" width="120" height="40">
<input type="email" required placeholder="you@example.com">
<div id="main" class="card highlighted" data-user-id="42"></div>

Try It: Essential HTML Attributes

Explore the most important HTML attributes in action. See how they control element behavior, appearance, and functionality.

Code Editor

<a href="https://developer.mozilla.org" target="_blank" title="Opens MDN">Link with attributes</a>
<img src="https://picsum.photos/id/64/120/80" alt="Portrait" width="120" height="80">
<input type="email" placeholder="you@example.com" required>
<button disabled>Disabled (boolean attribute)</button>
<div id="profile" class="card highlighted" data-user-id="42">id, class and data-* attributes</div>
<pre id="out"></pre>

Preview

What Are HTML Attributes?

HTML attributes provide additional information about HTML elements. They are name-value pairs that appear in the opening tag and control how elements behave, look, and interact with users and browsers.

Attribute Syntax:

<!-- Basic syntax -->
<element attribute="value">Content</element>

<!-- Multiple attributes -->
<img src="photo.jpg" alt="Description" width="300" height="200">

<!-- Boolean attributes -->
<input type="text" required disabled>

<!-- Global attributes -->
<div id="unique-id" class="css-class" title="Tooltip text">

Attribute Rules:

  • • Always in opening tag
  • • Space-separated from element name
  • • Use quotes around values
  • • Case-insensitive names
  • • No spaces around equals sign

Attribute Types:

  • • Global: Work on any element
  • • Specific: Element-specific only
  • • Boolean: True/false attributes
  • • Data: Custom data storage
  • • Event: JavaScript handlers

Global Attributes

Global attributes can be used on any HTML element. They provide universal functionality like identification, styling, accessibility, and behavior control.

Core Global Attributes

id

Unique identifier for an element

<div id="header">Unique element</div>

Used for CSS targeting, JavaScript selection, and anchor links

class

CSS class names for styling

<div class="card primary">Multiple classes</div>

Space-separated list of CSS classes

title

Tooltip text shown on hover

<button title="Click to save">Save</button>

Provides additional context and accessibility

Behavior & Accessibility

tabindex

Controls keyboard navigation order

<div tabindex="0">Focusable with tab</div>

Values: positive (order), 0 (natural), -1 (no tab)

hidden

Hides element from display

<div hidden>Not visible</div>

Boolean attribute - presence means hidden

lang

Language of element content

<span lang="es">Hola mundo</span>

Helps screen readers and translation tools

Element-Specific Attributes

Different HTML elements have their own specific attributes that control their unique functionality and behavior.

Link Attributes

href

Specifies the URL destination

<a href="https://example.com">Link</a>
<a href="#section">Internal link</a>
<a href="mailto:user@email.com">Email</a>

target

Where to open the linked document

<a target="_blank">New tab</a>
<a target="_self">Same tab (default)</a>

rel

Relationship to linked document

<a rel="noopener noreferrer">Safe external</a>
<a rel="nofollow">No SEO weight</a>

Image Attributes

src (required)

Image source URL

<img src="photo.jpg">
<img src="https://example.com/image.png">

alt (required)

Alternative text for accessibility

<img alt="Beautiful sunset over mountains">
<img alt="">  <!-- Decorative image -->
<img alt="Chart showing 50% growth">

width & height

Image dimensions in pixels

<img width="300" height="200">
<img width="100%">  <!-- CSS units work too -->

Security Note:

Always use rel="noopener noreferrer" withtarget="_blank" to prevent security vulnerabilities where the new page can access the original page's window object.

Data Attributes

Data attributes allow you to store custom data directly in HTML elements. They start withdata- and are perfect for JavaScript interaction and configuration.

HTML Syntax

<!-- Basic data attributes -->
<div data-user-id="12345">User Card</div>
<button data-action="save" data-target="form1">Save</button>

<!-- Multiple word attributes use hyphens -->
<div data-product-category="electronics">Product</div>
<span data-animation-duration="500">Animated text</span>

<!-- Complex data -->
<div data-config='{"theme": "dark", "lang": "en"}'>
  Widget
</div>

JavaScript Access

// Access via dataset property
const element = document.querySelector('.user-card');

// Get data attributes
const userId = element.dataset.userId;      // "12345"
const category = element.dataset.productCategory; // camelCase

// Set data attributes
element.dataset.status = 'active';
element.dataset.lastLogin = Date.now();

// CSS selector
document.querySelector('[data-action="save"]');

Use Cases

  • • Configuration settings
  • • User IDs and references
  • • Animation parameters
  • • Analytics tracking
  • • Component state
  • • API endpoints

Best Practices

  • • Use lowercase and hyphens
  • • Keep names descriptive
  • • Don't store sensitive data
  • • Validate data before use
  • • Use JSON for complex data

CSS Styling

/* CSS attribute selectors */
[data-status="active"] {
  color: green;
}

[data-theme="dark"] {
  background: #333;
}

Boolean Attributes

Boolean attributes represent true/false values. Their presence means true, their absence means false. No value is needed.

Common Boolean Attributes

required

Makes form field mandatory

<input type="email" required>
<textarea required></textarea>

disabled

Disables form elements

<button disabled>Can't click</button>
<input type="text" disabled>

checked

Pre-selects checkboxes/radios

<input type="checkbox" checked>
<input type="radio" checked>

readonly

Makes input read-only

<input type="text" value="Can't edit" readonly>

Syntax Variations

All these formats are equivalent and valid:

<!-- Minimized (recommended) -->
<input required>

<!-- Empty value -->
<input required="">

<!-- Attribute name as value -->
<input required="required">

<!-- Any value (still true) -->
<input required="true">
<input required="false">  <!-- Still true! -->

Important Note

For boolean attributes, any value (even "false") makes the attribute true. To make it false, remove the attribute entirely.

JavaScript Control

// Enable/disable elements
element.disabled = true;   // Add attribute
element.disabled = false;  // Remove attribute

// Check status
if (element.hasAttribute('disabled')) {
  // Element is disabled
}

Attribute Best Practices

Good Practices:

  • Always quote attribute values

    Use quotes even for single words for consistency

  • Use meaningful attribute values

    Choose descriptive IDs and class names

  • Include required accessibility attributes

    Always use alt for images, labels for inputs

  • Validate attribute values

    Use proper URLs, email formats, etc.

Avoid These:

  • ✗
    Unquoted attribute values

    Can break with spaces or special characters

  • ✗
    Duplicate IDs

    IDs must be unique across the entire page

  • ✗
    Missing required attributes

    Like alt for images or href for links

  • ✗
    Inline styles instead of classes

    Use CSS classes for maintainable styling

Professional Tips:

Performance:

  • • Minimize inline styles
  • • Use efficient selectors
  • • Avoid excessive data attributes
  • • Validate HTML regularly

Accessibility:

  • • Use semantic attributes
  • • Include ARIA attributes when needed
  • • Test with screen readers
  • • Provide alternative content

HTML Attributes — step by step

1 / 4
1

Understand attribute syntax

Attributes are written inside the opening tag as name='value' pairs. They provide additional information or behavior to elements.

1 of 4
🔍id Must Be Unique
The id attribute must be unique across the entire document. Duplicate IDs cause JavaScript querySelector to return only the first match and break CSS styling for subsequent elements. Use class for repeated patterns.

🎯 Quick Check

How do you store custom data on an HTML element that JavaScript can access?

HTML Attributes: summary

Key points

  • Boolean attributes like required, disabled and checked are true just by being present.
  • id must be unique on the page; class can repeat and hold several space-separated names.
  • Always quote attribute values, especially values that contain spaces.
  • Custom data goes in data-* attributes and is readable from JavaScript through element.dataset.

Frequently asked questions

›What is the difference between id and class?

An id identifies exactly one element and is used for anchors, labels and JavaScript lookups. A class groups any number of elements for styling.

›Does disabled="false" enable a button?

No. Any presence of a boolean attribute makes it true. To enable the button, remove the disabled attribute entirely.