HTML Attribute ID
HTML Attribute id
can be used to specify a unique if for an HTML element.
- No two elements in an HTML document can have the same
id
value - The id value is case sensitive
- The id value must contain at least one character, cannot start with a number, and cannot contain whitespaces (like spaces, tabs, etc.,)
- The id attribute value can be used to apply specific styles to the respective HTML elements
- The id attribute value can be used by Javascript to access and manipulate HTML elements
<h1 id="head">Heading</h1>
<p id="para">Paragraph Text</p>
<div id="section">
<h1>Heading</h1>
<p>Paragraph text within the div</p>
</div>
In the below example, the id
values across the elements are not the same as they are case-sensitive.
<h1 id="head">Heading One</h1>
<h1 id="Head">Heading Two</h1>
<h1 id="heaD">Heading Three</h1>
ID Attribute used for styling
The id attribute value head
can be accessed using a hash #head
to apply styles within the style element or CSS file.
In the below example, when the page is loaded, this style will apply a background-color
of gray
to an element with id head
.
<style>
#head {
background-color: gray;
}
</style>
ID Attribute used for scripts
Javascript can perform certain tasks on an element with a id
attribute by accessing the element using the method getElementById()
within the script.
In the below example, when the Javascript method highlightHeading()
is invoked, the script will turn the text color to red
on the element containing the id head
.
<script>
function highlightHeading() {
var x = document.getElementById("head");
x.style.color = "red";
}
</script>
Examples
The below example has the markup that explains all the above examples.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#head {
background-color: gray;
}
</style>
</head>
<body>
<h1>HTML ID Attribute</h1>
<button onclick="highlightHeading()">Highlight Heading</button>
<h2 id="head">Heading One</h2>
<p id="para">Paragraph One text goes here.</p>
<div id="section">
<h3>Heading</h3>
<p>Paragraph text within the div</p>
</div>
<script>
function highlightHeading() {
var x = document.getElementById("head");
x.style.color = "red";
}
</script>
</body>
</html>
Overall
HTML ID Attribute comes in handy for applying styles and scripts on a single HTML element in an HTML document.