HTML Id
In this page:
<tagname id="idname">content</tagname>
<style>
#idname {
property: value;
}
</style>
What is the id Attribute?
The id attribute defines a completely unique identifier for an HTML element. Unlike classes, an ID can only be assigned to one single element on an HTML page.
Example: What is the id Attribute?
<p id="intro">This paragraph has a unique id</p>
Styling with IDs in CSS
To target and style an ID inside your stylesheet, you use a hash symbol (#) followed by the exact ID name. ID selectors have a very high specificity rating, meaning they override standard class and element styling rules.
Example: Styling with IDs in CSS
<style>
#intro {
font-weight: bold;
}
</style>
<p id="intro">Styled by id</p>
Creating Jump Links with Anchor IDs
You can use IDs to build links that jump directly to specific sections on a long webpage. By setting the href of an anchor link to match an element's ID (prefixed with a hash #), the browser will automatically scroll to that element when clicked.
Example: Creating Jump Links with Anchor IDs
<a href="#section1">Jump to Section 1</a>
<h2 id="section1">Section 1</h2>
Targeting IDs in JavaScript
JavaScript relies heavily on IDs to locate and manipulate specific elements dynamically. The document.getElementById method is one of the fastest and most reliable ways to capture a specific element in your scripts.
Example: Targeting IDs in JavaScript
<script>
document.getElementById('intro');
</script>
<p id="intro">Targeted by script</p>
Class vs. ID - When to Use Which
Choosing between classes and IDs is easy when you remember this rule: use classes for styles you want to repeat across several elements, and use IDs to identify a single, unique element on the page.
Example: Class vs. ID - When to Use Which
<p class="highlight">Repeated style via class</p>
<p id="main-title">Unique element via id</p>
- Using the same ID attribute on multiple elements within a single HTML page.
- Writing a hash symbol (#) inside the HTML id attribute itself.
- Misspelling or mismatching uppercase and lowercase letters in your jump links or scripts.
- The id attribute assigns a completely unique identifier to a single HTML element on a webpage.
- Style individual IDs inside CSS using a hash prefix followed by the exact ID name.
- Use IDs to create convenient on-page jump links and to quickly target specific elements with JavaScript.
The id attribute is fully supported across all modern and legacy web browsers natively.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: