HTML id Attribute Tag Explained: How to Use IDs in HTML for Styling, Navigation, and JavaScript
By Pramod Behera · Updated: September 16, 2026 · 18 min read
- How to Use the HTML id Attribute for CSS, JavaScript, and Page Anchors
- Quick Recap: What Makes id Different
- Purposes of the id Attribute
- Example 1: Styling with CSS
- Example 2: JavaScript Interaction
- Example 3: Unique Element Styling
- Tag & Attribute Breakdown
- id vs class: When to Use Which
- id vs name: Two Similar-Looking Attributes
- Using id for Page Navigation (Anchor Links)
- Naming Rules and Best Practices for id Values
- id as an HTML5 Global Attribute
- Real-World Uses of the id Attribute
- Why id Matters for SEO and Accessibility
- Accessibility Considerations
- Common Mistakes to Avoid
- Best Practices Checklist
- Try It Yourself – Live Code Preview
- Practice Exercises
- Frequently Asked Questions
How to Use the HTML id Attribute for CSS, JavaScript, and Page Anchors
The id attribute in HTML is used to uniquely identify an element within a webpage. Unlike class, which can be used on multiple elements, an id must be unique on a page. This single rule is what makes id so powerful: because the browser can guarantee there is only one element carrying that exact identifier, it becomes the most precise "hook" you have for styling one specific element, wiring up one specific piece of JavaScript behaviour, or linking a visitor straight to one specific section of a long page. Every element you write in HTML — a heading, a paragraph, a div, a button, a footer — can carry an id attribute, and once it does, that element effectively gets its own personal address inside the document.
If you have already worked through the earlier tutorials in this HTML series, you have seen how tags define structure and how attributes like href, src, and class add extra information to those tags. The id attribute belongs to that same family of attributes, but it plays a very specific role: identity rather than grouping. Think of class as a label you can pin on many people wearing the same uniform, while id is more like a passport number — it belongs to exactly one person and nobody else on the page should share it.
Quick Recap: What Makes id Different
Across this HTML tutorial series you have already met several attributes that shape how a page looks and behaves, from href on anchor tags to class for grouping elements that share the same styling. The id attribute rounds out that picture by giving you a way to mark exactly one element as unique. Where class answers the question "which group of elements should look or behave this way?", id answers a completely different question: "which single, specific element am I talking about?" Keeping this distinction clear from the start will save you from a lot of confusion later, especially once a page grows to include dozens of divs, sections, and interactive components.
🟡 Purposes of the id Attribute
The id attribute is not tied to just one job — it is genuinely useful in three very different areas of front-end development, and understanding all three is what makes id click as a concept:
- Styling specific elements with CSS – targeting exactly one element with a CSS rule using the # selector.
- Targeting elements using JavaScript – grabbing exactly one element with document.getElementById() so you can read or change it.
- Linking to specific sections on the same page (anchor links) – jumping a visitor straight to a heading or block using a hash link.
Notice that all three purposes rely on the same underlying guarantee: uniqueness. CSS can safely style "the one element with this id" without worrying it will accidentally restyle five other unrelated elements. JavaScript can safely fetch "the one element with this id" without needing to loop through a collection. And a browser can safely jump to "the one element with this id" without any ambiguity about where the visitor should land. This is exactly why the id attribute is considered one of the core building blocks of practical, real-world HTML, right alongside class, href, and src.
✅ Example 1: Styling with CSS: -👇
<!DOCTYPE html>
<html>
<head>
<style>
#main-title {
color: green;
font-size: 24px;
}
</style>
</head>
<body>
<h1 id="main-title">Welcome to My Website www.learntosap.com</h1>
</body>
</html>
In this example, the h1 element carries id="main-title", and the CSS rule #main-title targets it directly by that id, turning the heading green and enlarging its font size. The hash symbol (#) in CSS is the id selector — it tells the browser "find the one element whose id matches the text that follows, and apply these styles to it, and only it." Because ids are unique, this selector is extremely predictable: there is never a risk of the rule accidentally cascading onto other headings elsewhere on the page, which is a real possibility if you had used a generic element selector like h1 instead.
✅ Example 2: JavaScript Interaction -👇
<!DOCTYPE html>
<html>
<body>
<p id="message">Click the button to change this text.</p>
<button onclick="document.getElementById('message').innerText = 'Text changed!'">Click Me</button>
</body>
</html>
Click the button to change this text.
Here, the p element is given id="message", and the button's onclick handler calls document.getElementById('message') to fetch that exact paragraph and then changes its innerText property. This is the classic pattern behind almost every interactive HTML page you have ever used: an element gets a unique id, JavaScript looks that id up, and then reads or rewrites something about that element — its text, its style, its visibility, or its contents. Without a unique id, JavaScript would have no reliable, single-element way to say "this exact paragraph, not any other paragraph on the page."
✅ Example 3: Unique Element Styling -👇
<!DOCTYPE html>
<html>
<head>
<style>
#footer-note {
text-align: center;
color: gray;
}
</style>
</head>
<body>
<footer id="footer-note">© 2025 LearntoSAP</footer>
</body>
</html>
This third example shows id being used on a semantic element, footer, rather than a generic div. The id="footer-note" gives that particular footer block a unique hook that the CSS rule #footer-note can target to center its text and mute its color to gray. This pattern — a semantic tag plus a unique id — is very common in production websites, because it lets you keep the meaningful HTML5 element (footer, header, nav, section) while still having a precise handle for styling that one instance of it.
🔍 Tag & Attribute Breakdown-
| Syntax | Purpose |
|---|---|
| id="value" | Assigns a unique identifier to a single HTML element |
| #value { ... } | CSS id selector; styles only the element with that exact id |
| document.getElementById('value') | JavaScript method that returns the single element with that id |
| <a href="#value"> | Anchor link that scrolls the browser to the element with that id |
| class="value" | Assigns a shared, reusable label that can appear on many elements |
id vs class: When to Use Which
The deciding question is simple: are you describing one specific element, or a group of elements that should all share the same treatment? If you are targeting a single hero heading, a single navigation bar, or a single "message" paragraph that JavaScript will update, id is correct because it guarantees you are only ever talking about that one element. If you are styling every card in a product grid, every warning message on a form, or every button that should look the same, class is correct because it can be reused across as many elements as you like without breaking any rule of valid HTML.
A common beginner mistake is repeating the same id on several elements just because they need the same style — for example, giving three different buttons id="btn" so a single CSS rule applies to all of them. This is invalid HTML: an id is only supposed to appear once per page, and browsers, JavaScript, and assistive technology all assume that uniqueness. The correct fix is to use a shared class, such as class="btn", for the styling that all three buttons have in common, and reserve id for only the one button (if any) that needs to be individually targeted by JavaScript or linked to directly.
id vs name: Two Attributes That Look Similar but Do Different Jobs
Beginners sometimes confuse id with another attribute, name, especially inside HTML forms, because both can appear on the same input element and both look like simple text labels. The difference matters a great deal in practice: id is a front-end hook used by CSS and JavaScript inside the browser, while name is the key that gets sent to the server when a form is submitted. An input can perfectly well carry both — id="email" so a <label for="email"> and your JavaScript can find it, and name="email" so the server-side script processing the form knows which value is which once the data arrives. Leaving out id does not break form submission, but it does break label association and JavaScript targeting; leaving out name does not break styling, but it does mean that field's value will not be included when the form is submitted.
Using id for Page Navigation (Anchor Links)
<a href="#pricing">Jump to Pricing</a>
...
<h2 id="pricing">Pricing Plans</h2>
The third major purpose of id — linking to specific sections on the same page — is exactly what powers the Table of Contents at the top of this article. Each entry in that list is an anchor tag whose href is a hash symbol followed by an id, such as href="#faq", and somewhere further down the page there is a heading carrying id="faq". Clicking the link instantly scrolls the browser to that heading, with no JavaScript required at all; this behaviour is built directly into HTML. This same technique is what lets you share a link that opens a page and jumps straight to one section, such as a specific FAQ answer or a specific pricing tier, simply by appending #section-id to the end of a URL.
Naming Rules and Best Practices for id Values
- Start the id value with a letter, not a digit, since some CSS and JavaScript selectors behave unpredictably with numeric leading characters.
- Use only letters, digits, hyphens, and underscores, and avoid spaces entirely — a space would split the id into two separate tokens for CSS selectors.
- Keep id values lowercase and hyphenated, such as main-title or footer-note, so they stay readable and consistent with common HTML and CSS naming conventions.
- Choose descriptive, meaningful names like nav-menu or hero-heading instead of vague ones like div1 or box2, so the id documents its own purpose.
- Never repeat the same id twice on one page — if two elements need identical styling, reach for a shared class instead.
id as an HTML5 Global Attribute
In HTML5, id is classified as a global attribute, which means it is valid on virtually every HTML element, from block-level tags like div, section, and article, to inline tags like span and a, to semantic tags like header, footer, and nav. This is different from attributes like href or src, which are only valid on specific tags such as a or img. Because id is global, you never need to worry about "is id allowed on this tag?" — the more relevant question is always "does this particular element genuinely need its own unique identity?"
Real-World Uses of the id Attribute
- In-page navigation menus – a sticky table of contents or a "back to top" link that jumps to a section by its id.
- Form field labelling – pairing a <label for="email"> with <input id="email"> so clicking the label focuses the correct field.
- JavaScript-driven widgets – modals, accordions, tabs, and live previews (like the code editor further down this page) that are opened, closed, or updated by referencing a unique id.
- Analytics and testing hooks – developers and QA engineers often rely on stable id values to reliably locate one exact element for tracking or automated tests.
Why id Matters for SEO and Accessibility
Search engines can use id-based anchor links to send visitors, and sometimes even search result "jump links," directly to a relevant section of a long page, such as a specific FAQ answer or a specific how-to step, which improves the experience for users arriving from search. When a long tutorial like this one uses id values on every major heading, search engines can index each section almost like its own mini-answer, which is part of why well-structured, id-linked headings tend to perform better for "how to" and definitional queries.
For accessibility, pairing <label for="id"> with a matching input id is one of the most important things you can do: it lets a screen reader correctly announce which label belongs to which form field, and it lets sighted mouse and touch users click the label text itself to focus or activate the corresponding control. This one small habit — matching a label's for attribute to an input's id — is consistently flagged in accessibility audits as one of the highest-impact, lowest-effort fixes a developer can make, precisely because it depends entirely on getting the id attribute right.
Accessibility Considerations
- Screen readers rely on unique ids to correctly associate a <label> with its <input>, and to correctly resolve aria-describedby or aria-labelledby references that point at an id.
- Keyboard users benefit from "skip to content" links that use an id-based anchor, such as href="#main-content", to bypass repetitive navigation.
- Duplicate ids can silently break assistive technology, since a screen reader or browser API that looks up one id by definition can only ever find the first (or an unpredictable) match.
Common Mistakes to Avoid
❌ Mistake 1 – Reusing the same id on multiple elements
An id must be unique; if several elements need the same style, use a shared class instead.
❌ Mistake 2 – Using id purely for styling that should be reusable
If the same visual treatment will be needed on more than one element eventually, class is the more future-proof choice.
❌ Mistake 3 – Including spaces or starting an id with a number
Both can cause CSS selectors and JavaScript lookups to fail or behave inconsistently across browsers.
❌ Mistake 4 – Forgetting that anchor links are case-sensitive
href="#Faq" will not match id="faq"; the id and the link fragment must match exactly, including letter case.
❌ Mistake 5 – Hardcoding vague ids like div1, box2, or test
Meaningless ids make a codebase harder to maintain and give no clue to future developers about the element's role.
Best Practices Checklist
✔️ 1) Reserve id for elements that are genuinely unique
A single hero heading, a single nav bar, a single "message" box that JavaScript updates.
✔️ 2) Use class for anything shared across multiple elements
Buttons, cards, list items, and repeated components belong here instead.
✔️ 3) Keep id names lowercase, hyphenated, and descriptive
main-nav reads far better than a meaningless number or single letter.
✔️ 4) Pair form labels and inputs with matching id and for values
This is one of the simplest, highest-impact accessibility habits you can build.
✔️ 5) Use id-based anchors for long-form content
A table of contents, like the one at the top of this page, makes long tutorials far easier to navigate.
Try It Yourself (Copy This Code and Paste. See how it works)
Live Code Preview
Practice Exercises: Test the HTML id Attribute
- Give an h2 heading a unique id and write a CSS rule using # that changes its color.
- Create a paragraph with an id and a button that uses document.getElementById() to change its text when clicked.
- Build a short table of contents with 3 anchor links, each pointing to an id placed on a heading further down the same page.
- Pair a <label for="..."> with an <input id="..."> so clicking the label focuses the input field.
- Deliberately give two elements the same id, then explain in your own words why this is invalid and what could go wrong.
Frequently Asked Questions About the HTML id Attribute
What is the id attribute used for in HTML?
The id attribute in HTML is used to uniquely identify an element within a webpage, and that unique identity can then be targeted by CSS for styling, by JavaScript for interaction, or by an anchor link for in-page navigation.
What is the difference between id and class in HTML?
An id must be unique on a page and identifies exactly one element, while a class can be applied to multiple elements at once, making class the right choice for shared styling and id the right choice for a single, specific target.
Can two elements have the same id in HTML?
No, an id must be unique on a page, so giving two elements the same id is invalid HTML and can cause CSS, JavaScript, and anchor links to behave unpredictably since only one element is supposed to match that identifier.
How do you link to an id within the same page?
You create an anchor link by adding a hash symbol followed by the id value as the href of an a tag, such as href="#section-name", which scrolls the browser directly to the element carrying that id.
Can id be used to select elements in JavaScript?
Yes, JavaScript's document.getElementById() method is built specifically to fetch a single element by its id attribute, making id the fastest and most direct way to target one exact element for interaction.
What characters are allowed in an HTML id value?
An HTML id value should start with a letter and can contain letters, digits, hyphens, and underscores, while spaces and most special characters should be avoided so the id works reliably with CSS selectors and JavaScript.