HTML Id

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

Using CSS to style an element with ID.

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

Using Javascript to modify an element with ID.

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 id to 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 id is case-sensitive. Therefore, animal and Animal are two different ids.
  • You can not use space in HTML id. If you use a space in an id, it will be treated as two separate id values. 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.