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.

Example

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

<!-- Multiple attributes, separated by spaces -->
<img src="/assets/images/tutorials/html-example-photo.webp" alt="A sample 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.

Example

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.

Example

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.

Example

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.

Example

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.

Example

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.

Example

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.

Example

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.

Example

HTML
<!-- 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.

❓ FAQ

Q Do attribute values always need quotes? What's the difference between single and double quotes?
A HTML5 requires attribute values to be wrapped in quotes — double quotes ("value") are the industry standard. Single quotes ('value') are also valid in HTML5, but double quotes are preferred for readability and consistency. Use single quotes only when the value itself contains double quotes (like title='He said "Hello"'). Omitting quotes may work in some cases but can cause parsing errors — never recommended.
Q What's the difference between id and class? When should I use each?
A id is like an ID card — each page can only have one element with a given id, making it unique. class is like a class name — multiple elements can share the same class, making it reusable. In practice, use class 90% of the time because style reuse is the norm. id has higher CSS specificity, but don't abuse it just for priority. Remember: id for JavaScript targeting, class for CSS styling.
Q Why do some attributes like disabled and checked not need a value?
A These are called "boolean attributes" — their mere presence means "on," and their absence means "off." Like a light switch: the switch being there means on, absent means off. You don't need to say "switch=on." HTML5 states boolean attributes cannot be set to false; to disable, simply remove the attribute. Example: <input disabled> disables the input; remove disabled to enable it. Don't write disabled="true" (redundant) or disabled="false" (won't disable — a common mistake).

📖 Summary

📝 Exercises

  1. Attribute Combination Practice: Create a page containing the following elements:
  1. 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%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏