What is the id attribute used for?
The id attribute is used to assign an element a unique identifier within an HTML document.
It lets you precisely reference a specific element: in CSS, JavaScript, and page navigation.
1. Main purpose
id sets a unique name for an element.
This name should appear only once on the page.
Example:
<p id="intro">This is the first paragraph.</p>Now this paragraph can easily be found and changed with CSS or JavaScript.
2. Use in CSS
Through id, you can style a specific element using #name:
<p id="intro">Example text.</p>#intro {
color: blue;
font-weight: bold;
}Here the style applies only to this paragraph, even if the page has other <p> elements.
3. Use in JavaScript
id lets you access the element directly from a script:
<p id="message">Hello!</p>
<script>
document.getElementById("message").textContent = "Changed text";
</script>The getElementById() method looks for the element with the specified identifier.
4. Use for anchor links
id can be used to create jumps to specific parts of the page.
<a href="#contacts">Contacts</a>
<section id="contacts">
<h2>Our contacts</h2>
</section>On click, the page automatically scrolls to the element with this id.
5. Usage rules
- The identifier must be unique within the document.
- It must not contain spaces.
- It can include letters, digits, hyphens, and underscores (
id="user-name"). - Character case matters (
id="Header"andid="header"are different).
Summary:
| Property | Description |
|---|---|
| Purpose | Uniquely identifies an element |
| Where it applies | Any HTML tag |
| How it's used | In CSS (#id), JS (getElementById()), anchors (href="#id") |
| Limitation | Only one element with a given id per page |
In simple terms:
id is a unique "passport" for an element.
It's needed so you can precisely find, style, or change a specific element on the page.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.