The id Attribute
Give an element a unique identifier with id.
Syntax
<h2 id="chapter1">Chapter 1</h2>The id attribute gives an element a unique identifier. No two elements on a page should share the same id.
Why use id
- To link directly to a section of a page.
- To target a specific element from CSS or JavaScript.
You can jump to an element by adding #id to a URL.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer uses id="navbar" on a navigation element so CSS and JavaScript can target it uniquely.
- A page links to id="pricing" on the same page with href="#pricing" to create an in-page jump link.
- A JavaScript function calls document.getElementById("modal") to show or hide a specific modal dialog.
More examples
Unique id for CSS and JS targeting
Each id is unique on the page and lets CSS rules or document.getElementById() target that exact element.
<header id="site-header">
<h1>SoundsCode</h1>
<nav id="main-nav">
<a href="/">Home</a>
</nav>
</header>In-page anchor link using id
href="#intro" jumps the page to the element with id="intro" without a page reload.
<nav>
<a href="#intro">Introduction</a>
<a href="#examples">Examples</a>
</nav>
<section id="intro">
<h2>Introduction</h2>
</section>
<section id="examples">
<h2>Examples</h2>
</section>JavaScript targeting by id
getElementById uses the unique id to grab and control specific elements via JavaScript event listeners.
<button id="open-modal">Open</button>
<dialog id="confirm-dialog">
<p>Are you sure?</p>
<button id="close-modal">Close</button>
</dialog>
<script>
document.getElementById("open-modal")
.addEventListener("click", () =>
document.getElementById("confirm-dialog").showModal());
</script>
Discussion