The HTML id attribute is used to uniquely identify an element on a webpage, allowing it to be targeted for styling, scripting, and navigation.
- Must be unique within a single HTML document.
- Used by CSS (#id) to apply specific styles.
- Used by JavaScript to access and manipulate elements.
- Enables linking to specific sections using anchor links.
- Written as id="value" inside an HTML tag.
Syntax:
<tag id=""></tag>Note: This is a global attribute, it can be used in all the tags.
Examples of id Attribute
Here some examples discussed:
Example 1: Style the element with id "geeks".
<!DOCTYPE html>
<html>
<head>
<style>
#geeks {
color: green;
}
</style>
</head>
<body>
<h2>Welcome to GeeksforGeeks</h2>
<h1 id="geeks">Hi Geeks!</h1>
</body>
</html>
Output:

- Two headings are defined, with one having id="geeks".
- CSS targets the #geeks id selector.
- The selected heading is styled with green text color.
- This makes the heading visually distinct and highlighted.
Example 2: Styling properties to the specific id attribute value by fetching its id value.
<!DOCTYPE html>
<html>
<head>
<title>Id Attributes</title>
<style>
#gfg {
color: #009900;
font-size: 50px;
font-weight: bold;
text-align: center;
}
#geeks {
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<div id="gfg">GeeksforGeeks</div>
<div id="geeks">
A computer science portal for geeks
</div>
</body>
</html>
 Output:

- The HTML document contains two <div> elements with unique ids: gfg and geeks.
- CSS targets each id selector (#gfg and #geeks) to apply styles.
- The #gfg styles make the "GeeksforGeeks" text large, bold, and centered.
- The #geeks styles adjust the description text’s size and alignment.
Note: In HTML5, the id attribute can be used on any element. In HTML 4.01, it had restrictions (not allowed on some tags) and could not start with a number.
Use of ID attributes in JavaScript
In JavaScript, ID attributes uniquely identify HTML elements, enabling efficient selection and manipulation through methods like getElementById(). They serve as hooks for accessing specific elements for dynamic functionality and interaction.
<!DOCTYPE html>
<html>
<head>
<title>Using the id in Javascript</title>
<style>
#geeks {
font-size: 50px;
color: #009900;
font-weight: bold;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="geeks">GeeksforGeeks</div>
<button onclick="geeksResult()">Display text change</button>
<script>
function geeksResult() {
document.getElementById("geeks").innerHTML =
"A computer science portal for geeks";
document.getElementById("geeks").style.color = "black";
}
</script>
</body>
</html>
Output:

- In the above example Includes a div element with id "geeks", displaying "GeeksforGeeks" initially.
- Clicking the button triggers a JavaScript function called "geeksResult()".
- The function modifies the innerHTML of the div element to "A computer science portal for geeks".