Rules and Best Practices for IDs
- Use a distinct ID for each element within a document.
- Choose descriptive names such as
main-navigation,contact-form, orcourse-title. - Avoid spaces in ID values.
- IDs must not be empty.
- An ID value must not contain ASCII whitespace characters.
- IDs can contain many characters, but simple names using letters, digits, hyphens, and underscores are easier to manage.
- When using an ID in a CSS selector or JavaScript selector, remember that special characters may need escaping.
Using an ID in CSS
CSS uses the hash symbol (#) to select an element by ID.
<h1 id="main-title">HTML5 Mastery</h1>
<style>
#main-title {
color: navy;
font-size: 32px;
}
</style>The selector #main-title targets the element whose ID is main-title.
Using an ID in JavaScript
JavaScript can retrieve an element by its ID using document.getElementById().
<p id="message">Original message</p>
<script>
const message = document.getElementById("message");
message.textContent = "Welcome to Codementrix!";
</script>After the script runs, the paragraph displays the new text.
Important: Place scripts where the elements they need are available, or use suitable loading techniques such as a deferred external script. If an element with the specified ID does not exist, getElementById() returns null.
Using an ID as a Link Destination
An ID can identify a destination within a page.
<nav>
<a href="#pricing">View Pricing</a>
</nav>
<section id="pricing">
<h2>Pricing</h2>
<p>Explore our available plans.</p>
</section>When the user activates the link, the browser navigates to the element identified by pricing.
IDs Must Be Unique
Incorrect:
<p id="notice">First notice</p>
<p id="notice">Second notice</p>Correct:
<p id="notice-one">First notice</p>
<p id="notice-two">Second notice</p>Duplicate IDs make document references ambiguous and can cause unexpected results in scripts, fragment navigation, accessibility relationships, and CSS targeting.
4. The Class Attribute
The class attribute assigns one or more class names to an element. Classes are commonly used to apply CSS styles and identify groups of elements for JavaScript behavior.