The id attribute assigns an identifier to an HTML element. The id must be unique and a page can only have one element with that id. Ids are used by JavaScript and can also be used for CSS styling.

HTML Tutorial


An id attribute on a <p> element.

A paragraph with an id.

<p id="my-paragraph"
   A paragraph with an id.

Tip:  The id must be unique on the page.

Differences between Class and Id

An id can only be used once on a page, whereas a class can be used multiple times.

In CSS, classes are defined with a dot (.) and ids are defined with a hash (#).

Dot (.) and hash (#) selectors are called class selectors and id selectors respectively.

Two selectors: an id selector and a class selector -- each one styling a <div>.

The id of this div is alice -- #alice in CSS.

The class of this div is mint -- .mint in CSS.
  #alice { background-color: aliceblue; border: 1px solid #aaa; padding: 25px; }
  .mint { background-color: mintcream; border: 1px solid #aaa; padding: 25px; } 
  <div id="alice">
    The id of this div is alice -- #alice in CSS.
  <br />
  <div class="mint">
    The class of this div is mint -- .mint in CSS.

Creating Bookmarks with id and links

HTML bookmarks allow users to jump to specific locations on a web page.
Bookmarks are useful in long web pages. Their URLs are defined by an id prefixed with a #.

The link below scrolls the page to item 5 when clicked. The link is #item5.
Note: It's difficult to demonstrate bookmarks in a small box. It works best on a full page.

Item 1 content
Item 2 content
Item 3 content
Item 4 content
Item 5 content
<div><a href="#item5">Jump to Item 5</a></div>
<br />
<br />
<div id="item1">Item 1 content</div>
<div id="item2">Item 2 content</div>
<div id="item3">Item 3 content</div>
<div id="item4">Item 4 content</div>
<div id="item5">Item 5 content</div>

Note:  Bookmarks are also refered to as anchors.

Id and JavaScript

JavaScript can access an element by id with the getElementById() method.

Clicking the button calls a JavaScript function that locates the <div> by id and changes its text.

Hello World!

<div id="world-id">Hello World!</div>
<br />
<button onclick="toggle();">Toggle Text</button>


  let toggle = () => {
    let element = document.getElementById("world-id");
    if (element.innerHTML === "Hello World!") {
        element.innerHTML = "Hello Earth!";
    } else {
        element.innerHTML = "Hello World!";


You may also like