8.1 The id Attribute
Global attributes are attributes that can be used with any HTML element. They play a key role in identifying, classifying, and managing web page elements.
The id
attribute is used to uniquely identify an element on the page. The value of the id
attribute must be
unique within the entire HTML document. This attribute is often used in conjunction with CSS and JavaScript.
Syntax:
<element id="unique-id">...</element>
Usage Example:
#header {
background-color: #f4f4f4;
padding: 10px;
}
<div id="header">
<h1>Header</h1>
</div>
document.getElementById('header').style.color = 'blue';
Advantages:
- Unique Identification: allows you to uniquely identify elements on the page
- Styling: convenient for applying CSS styles
- DOM Manipulation: easily access elements with JavaScript
8.2 The class Attribute
The class
attribute is used to assign one or more classes to an element. These classes can be used to apply
CSS styles and manipulate elements with JavaScript. Unlike id
, class values are not required to be unique.
Syntax:
<element class="class-1 class-2">...</element>
Usage Example:
.highlight {
background-color: yellow;
}
.bold {
font-weight: bold;
}
<p class="highlight">This text is highlighted in yellow.</p>
<p class="bold">This text is bold.</p>
<p class="highlight bold">This text is bold and highlighted in yellow.</p>
Advantages:
- Multiple Classes: allows assigning multiple classes to an element
- Grouping Elements: easily apply styles to groups of elements
- DOM Manipulation: easily work with groups of elements via JavaScript
8.3 The data-* Attributes
The data-*
attributes allow storing custom data in HTML elements. These attributes start with the data-
prefix and can have any value. They are often used to store information that may be useful for JavaScript.
Syntax:
<element data-key="value">...</element>
Usage Example:
<div data-user-id="12345" data-role="admin">
User with ID 12345, role - admin.
</div>
// Find the first element on the page with the data-user-id attribute
const userElement = document.querySelector('[data-user-id]');
// Get the value of the data-user-id attribute and log it to the console
console.log(userElement.dataset.userId); // Output: 12345
// Get the value of the data-role attribute and log it to the console
console.log(userElement.dataset.role); // Output: admin
Advantages:
- Data Storage: convenient for storing and transmitting data related to elements
- Access via JavaScript: easily access and modify data via the dataset API
- Flexibility: allows adding any data without breaking HTML standards
GO TO FULL VERSION