English العربية Português Japanese

HTML Attributes

Attributes provide additional configuration information for HTML tags, making elements' behavior and appearance richer.

What Are Attributes

HTML attributes are special keywords written within the opening tag, used to configure tags in more detail. Attributes are written as name="value" inside the opening tag. A tag can have multiple attributes, separated by spaces.

HTML
<!-- Single attribute -->
<a href="https://example.com">This is a link</a>

<!-- Multiple attributes, separated by spaces -->
<img src="photo.jpg" alt="A landscape photo" width="800" height="600">

<!-- Attribute values are recommended to be wrapped in double quotes, but single quotes also work -->
<p title='A tooltip text'>A paragraph with a tooltip</p>
▶ Try It Yourself

In the examples above, href, src, alt, width, height, and title are all attribute names, and the content inside quotes are the specific attribute values. Attribute names are always lowercase, and double quotes are recommended for attribute values.

📌 Attribute Writing Convention: In HTML5, quotes around attribute values can be omitted (if the value doesn't contain special characters like spaces), but it's strongly recommended to always use double quotes. This makes the code clearer and avoids unexpected errors.

Common Global Attributes

Global Attributes are attributes that can be used on any HTML tag. Here are the most commonly used global attributes:

id — Unique Identifier

The id attribute assigns a unique identifier to an element. Within the same page, each id can only be used once. It's commonly used for anchor links, CSS selectors, and JavaScript operations.

HTML
<h1 id="page-title">Welcome to My Website</h1>
<!-- #page-title can be used to jump to this heading position -->
<a href="#page-title">Jump to Title</a>
▶ Try It Yourself

class — Class Name

The class attribute assigns one or more class names to an element. Unlike id, the same class name can be reused across multiple elements and is the primary method for CSS styling and JavaScript selection.

HTML
<!-- Multiple elements can use the same class -->
<p class="highlight">This text will be highlighted</p>
<p class="highlight">This text will also be highlighted</p>

<!-- One element can have multiple classes, separated by spaces -->
<div class="box bordered rounded">This is a rounded box with a border</div>
▶ Try It Yourself

style — Inline Styles

The style attribute allows writing CSS styles directly within a tag. While not recommended for heavy use (it's better to keep styles in separate CSS files), it's very convenient for quick testing or dynamically overriding styles.

HTML
<p style="color: red; font-size: 18px;">This is large red text</p>
<div style="background: #f0f0f0; padding: 10px; border-radius: 5px;">
  This is a rounded box with a background color
</div>
▶ Try It Yourself

title — Tooltip Text

The title attribute provides additional information for an element. When the user hovers over the element, the browser displays a tooltip.

HTML
<p title="This is a tooltip text">Hover over this text to see what happens</p>
<abbr title="HyperText Markup Language">HTML</abbr>
▶ Try It Yourself

Global Attributes Summary

Attribute Purpose Uniqueness Frequency of Use
id Unique identifier for element, used for anchors, CSS, JS Page-unique ⭐⭐⭐⭐⭐
class Assigns class name to element, used for CSS / JS Reusable ⭐⭐⭐⭐⭐
style Write CSS styles directly within the tag ⭐⭐⭐
title Displays tooltip text on mouse hover ⭐⭐
lang Declares the language of the element's content ⭐⭐
dir Specifies text direction (ltr / rtl)

Boolean Attributes

Boolean Attributes are a special type of attribute — they don't need a value; simply appearing means "on/true". Common boolean attributes include disabled, checked, readonly, and required.

HTML
<!-- Disabled input field -->
<input type="text" disabled>

<!-- Pre-checked checkbox -->
<input type="checkbox" checked> I agree to the terms

<!-- Read-only input field -->
<input type="text" value="Read-only content" readonly>

<!-- Required field -->
<input type="email" required>
▶ Try It Yourself

Boolean attributes can also be written as name="name", for example disabled="disabled". Both forms produce exactly the same effect. The concise form (attribute name only) is recommended.

✅ Best Practice: For boolean attributes, writing only the attribute name (no value) is recommended — the code is more concise. Only use the name="name" form when XHTML syntax strictly requires it.

Custom Data Attributes data-*

HTML5 introduced a very flexible feature: custom data attributes. You can create your own attributes on any HTML tag, as long as the attribute name starts with data-. Its purpose is to store additional data within HTML tags for use by JavaScript and CSS.

For example, imagine you have a product list and want to store each product's price and stock quantity — this data doesn't need to be displayed on the page, but JavaScript needs to read it for interactive logic.

HTML
<!-- Store custom data within tags -->
<ul>
  <li data-product-id="101" data-price="29.9" data-stock="50">T-Shirt - $29.9</li>
  <li data-product-id="102" data-price="99.9" data-stock="20">Backpack - $99.9</li>
  <li data-product-id="103" data-price="199" data-stock="0">Headphones - $199 (Sold Out)</li>
</ul>
▶ Try It Yourself

In this example, data-product-id, data-price, and data-stock are all attributes we defined ourselves. They won't affect the page's display, but JavaScript can easily read them.

JavaScript
// Access data-* via the dataset API
const items = document.querySelectorAll('li');
items.forEach(item => {
  console.log(item.dataset.productId);  // "101", "102", "103"
  console.log(item.dataset.price);      // "29.9", "99.9", "199"
});
▶ Try It Yourself

Naming Rules: In HTML, use data-user-name (hyphenated). In JavaScript, the corresponding access is dataset.userName (camelCase). The first letter after each hyphen is automatically converted to uppercase.

HTML + JS Mapping
<!-- data-* attributes in HTML -->
<div data-user-name="Zhang San" data-user-age="20">User Info</div>

<!-- Corresponding JavaScript dataset access -->
<!-- div.dataset.userName → "Zhang San"    (data-user-name) -->
<!-- div.dataset.userAge → "20"            (data-user-age) -->
▶ Try It Yourself
📌 Usage Scenarios: data-* attributes are very common in front-end development, for example to store user IDs, sort states, button types, chart configurations, etc. They are more intuitive than maintaining a separate data object in JavaScript, because the data "lives together" with the corresponding HTML structure. You'll use this feature extensively in later JavaScript chapters.
⚠️ Note: data-* attributes should only be used to store data related to page display, not as a replacement for databases or backend storage. Sensitive information (such as passwords, API keys) must never be placed in data-* — because anyone can see it by viewing the page's source code.

📖 Summary

📝 Exercises

  1. Attribute Combination Practice: Create a page containing the following elements:
    - A paragraph with id, class, and style attributes;
    - A link with a title attribute (hover to see the tooltip);
    - An input field with the disabled attribute (grayed out, not clickable).
  2. data-* Practice: Create a product card list where each card uses data-* attributes to store the product name, price, and stock. Then use JavaScript to read this data in the browser console via document.querySelectorAll and dataset.
100%