Skip to main content

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:

html
<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:

html
<p id="intro">Example text.</p>
css
#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:

html
<p id="message">Hello!</p> <script> document.getElementById("message").textContent = "Changed text"; </script>

The getElementById() method looks for the element with the specified identifier.


id can be used to create jumps to specific parts of the page.

html
<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" and id="header" are different).

Summary:

PropertyDescription
PurposeUniquely identifies an element
Where it appliesAny HTML tag
How it's usedIn CSS (#id), JS (getElementById()), anchors (href="#id")
LimitationOnly 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.