The id Attribute

The id Attribute

<h2 id="C4">Chapter 4</h2>
  • Specifies a unique id for an HTML element (the value must be unique within the HTML document).
  • The id value can be used by CSS and JavaScript to perform certain tasks for a unique element with the specified id value.
  • Is case-sensitive.
  • In CSS, to select an element with a specific id, write a hash (#) character, followed by the id of the element.

Using The id Attribute in JavaScript

function displayResult() {
  document.getElementById("myHeader").innerHTML = "Have a nice day!";

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

Difference Between Class and ID

<!-- A unique element -->
<h1 id="myHeader">My Cities</h1>

<!-- Multiple similar elements -->
<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>

An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements.

The id Attribute — Structure map

Clickable & Draggable!

The id Attribute — Related pages: