04. id Attribute
Introduction
Section titled “Introduction”The id attribute provides a unique identifier for an HTML element. It’s used for CSS styling, JavaScript targeting, anchor links, and form label associations. Each id value must be unique within a document. Understanding how to use the id attribute properly is essential for creating functional, accessible web pages.
Basic Usage
Section titled “Basic Usage”<div id="header">Header content</div><p id="intro">Introduction paragraph</p>Common Use Cases
Section titled “Common Use Cases”CSS Styling
Section titled “CSS Styling”<div id="main-content">Content</div>
<style> #main-content { max-width: 800px; margin: 0 auto; }</style>JavaScript Targeting
Section titled “JavaScript Targeting”<button id="submit-btn">Submit</button>
<script> document.getElementById('submit-btn').addEventListener('click', function() { // Handle click });</script>Anchor Links
Section titled “Anchor Links”<a href="#section1">Jump to Section 1</a><section id="section1"> <h2>Section 1</h2></section>Form Labels
Section titled “Form Labels”<label for="email">Email:</label><input type="email" id="email" name="email">Best Practices
Section titled “Best Practices”Unique IDs
Section titled “Unique IDs”<!-- Good: Unique IDs --><div id="header">Header</div><div id="footer">Footer</div>
<!-- Avoid: Duplicate IDs --><div id="content">Content 1</div><div id="content">Content 2</div>Descriptive Names
Section titled “Descriptive Names”<!-- Good: Descriptive --><div id="main-navigation">Navigation</div>
<!-- Avoid: Generic --><div id="div1">Content</div>