An HTML id is an attribute that can be added to an HTML element to give it a unique identifier. It is used in CSS or JavaScript to select and style the element, or to add behavior to it with JavaScript. For example,
<h2 id="title">Programiz</h2>
<style>
#title {
color: red;
}
</style>
Browser output
In the above example, element <h2> with class name title is styled with #title selector.
Note: We use # before id in CSS.
HTML id with Javascript
The id attribute allows javascript to access the element using getElementById API. For example,
<h1 id="heading">Main Heading</h1>
<script>
let element = document.getElementById("heading");
element.innerHTML = "Content"
</script>
Browser output
In the above example, we have used document.getElementById("heading") to access the HTML element where the heading is the name of the id in <h1> element. Then, the innerHTML property changes the content (the text inside the <h1> tag) from Main Heading to Content.
HTML id for Anchor links
Anchor links are used to jump to a specific part of the page for quick navigation. We can use HTML id to create anchor links. There are two steps to create an anchor link.
- Add an
idto an element.
<h1 id="main">Main Heading</h1>
- Create a hyperlink using id.
<a href="#main">Go to the top.</a>
Let's see an example of how this would work together in an HTML document.
<h1 id="heading">Main Heading</h1>
<p class="main-content">
This is a paragraph
</p>
<a href="#heading">Go to the top</a>
Here, clicking on the Go to top will scroll the page to the h1 tag with the id "heading".
Link anchor from another web page
The anchor can be linked from other websites too. For example,
<a href="programiz.com/html/head#title-tag"> Link </a>
Here, clicking on this link will take us to the URL programiz.com/html/head and then scroll to the element with the id title-tag.
Things to Note
- HTML
idis case-sensitive. Therefore,animalandAnimalare two different ids. - You can not use space in HTML
id. If you use a space in anid, it will be treated as two separateidvalues. So, instead of using my id as your id name use my-id.
Id vs Class
An HTML id and a class are both attributes that can be added to an HTML element to give it an identifier. The main difference between an id and a class is that an id is unique within an HTML document, while a class can be used multiple times on a page.
Moreover, we can only use one id in an HTML element while we can use multiple classes in an HTML element.