Id in HTML
? The id Attribute in HTML
The id attribute uniquely identifies an HTML element on a page.
Key Points About id
Must be unique within the entire HTML document
Used for styling with CSS (
#id)Used in JavaScript to select or manipulate elements (
document.getElementById())Can be targeted by URL fragments (e.g.,
example.com/page.html#section1) for direct linkingHelps with accessibility (labeling, landmarks)
Example
<h1 id="main-title">Welcome to My Website</h1><style> #main-title { color: blue; }</style><script> const title = document.getElementById('main-title'); title.textContent = 'Hello, World!';</script>Best Practices
Use meaningful, descriptive IDs (e.g.,
header,contact-form)Avoid spaces or special characters; use hyphens or underscores if needed
Don’t reuse the same
idon multiple elements
Want examples of how to style or manipulate elements using their id?