HTML ID Attribute with Examples

The ‘id‘ attribute in HTML is an unique identifier used to uniquely identify any element within a page. In simple words, we use id attribute to specify a unique id for an HTML element.

For example, if we have two elements of the same name within a web page or style sheet, we can use the id attribute to differentiate between elements that have the same name.

Hence, if an HTML element carries an id attribute as an unique identifier, it is possible to identify just that element and its content in the HTML document. We cannot use the same id for more than one element in an HTML document.

The id attribute can name any element whether it is a block-level element or inline-level element in the HTML document. Block-level elements by default start on a new line and take up the full width available. Some commonly used block elements are <div>, <p>, <h1> to <h6>, <footer>, etc. However, inline elements do not start on a new line and only take up as much width as necessary. Examples of inline elements are <span>, <a>, <img>, etc.

HTML id attribute is always placed in the opening HTML tag. It helps in identifying and targeting the element with CSS styles, JavaScript, or linking parts of a webpage within the same document or from different documents.

Basic Syntax to Use ID Attribute in HTML


We use id attribute to style one specific element on the HTML document or web page. Id attribute is always defined within the opening tag of the element as follows:

<tagname id="uniqueId">Content</tagname>

In the above syntax,

  • <tagname>: It represents the HTML tag used to create the element. It could be any valid HTML tag such as <div>, <p>, <span>, <a>, and so on.
  • id=”uniqueId”: This is the id attribute with its value set to “uniqueId”. The value of the id must be unique within the HTML document. This means no two elements should have the same id value because the id attribute identifies a specific element uniquely across the entire document.
  • Content: This is the content enclosed within the opening and closing tags. Depending on the tag, this could be text, other HTML elements, images, links, etc.
  • </tagname>: This is the closing tag that matches the opening tag. It signifies the end of the element.

Here are some examples with different tags and content:

Example 1:

<p id="intro">This is an introductory paragraph.</p>

Here, we have defined a paragraph (<p>) element with the id attribute set to “intro”.

Example 2:

<div id="mainContent">Here is the main content of the web page.</div>

In this example, we have defined a <div> element with an id attribute set to “mainContent”.

Rules for Values of ID Attribute


There are some specific rules to select a value of an id attribute in HTML that you should keep in mind. They are as:

(1) The value of an id attribute for each element must be unique within the HTML document. No two elements should have the same id value in a webpage. This is essential because the main purpose of the id attribute is to identify a specific element uniquely in HTML webpage.

(2) The id name is case-sensitive. This means that id=”Example” and id=”example” would be considered different identifiers.

(3) The value of an id attribute must not start with a numeric digit. Identifiers starting with a numeric digit may cause issues, especially in CSS and JavaScript.

(4) Id name should not contain white spaces or tabs.

(5) Id name can include letters (a-z, A-Z), digits (0-9), hyphens (-), underscores (_), colons (:), and periods (.). But id name starting with a colon or a period is mostly not recommended for compatibility and readability reasons.

(6) Select id values that are descriptive that provide some indication of the element’s purpose or content. This not only improves the readability of your code, but also helps in maintainability.

Here’s some valid examples of using id attribute with unique value:

Valid Example:

<div id="header">This is the header section of the page.</div>
<p id="first-paragraph">This is the first paragraph of text.</p>

Invalid Example:

<div id="123">This will not work well in CSS or JavaScript.</div>
<p id="unique id">Whitespace is invalid in an id.</p>

ID Selector in CSS: Syntax and Example


In CSS, an ID selector is denoted by a hash symbol (#) followed by the id name (or say id value). Then, we define the CSS properties within curly braces {}. The general syntax for using an Id in CSS is as follows:

#uniqueId {
    property: value;
    property2: value2;
    /* Add more properties as needed */
}

In the above syntax,

  • # : This is a hash symbol used to specify that the selector is an ID.
  • uniqueId: This is the unique identifier that we will assign to an HTML element using the id attribute. The value provided after the hash symbol (#) in CSS must match exactly with the id value used in the HTML id attribute. This includes being case-sensitive.
  • the HTML element.
  • Curly Braces {}: Inside the curly braces, we place the CSS properties with values that we want to apply to an element with the specified ID.

Example 3:

Let’s create an id named ‘myDiv’ that sets the text color to white and the background color to red.

CSS Code:

#myDiv {
    color: white;
    background-color: blue;
    padding: 20px;
    text-align: center;
}

Let’s use this id selector to apply styles to a <div> element in HTML.

HTML Code:

<div id="myDiv">This is a styled div.</div>

Complete code:

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {
    color: white;
    background-color: blue;
    padding: 20px;
    text-align: center;
}
</style>
</head>
<body>
    <div id="myDiv">This is a styled div.</div>
</body>
</html>

Output:
An example of HTML id attribute.

Linking to Specific Sections of a Webpage


We can use the id attribute to link to specific sections of a webpage, either on the same page or from a different page. This is commonly used for creating a table of contents or in-page navigation. Let’s take an example where we will perform linking to specific sections of a web page.

Example 4:

<!DOCTYPE html>
<html>
<body>
  <h2>Table of Contents</h2>
  <ul>
    <li><a href="#section1">Go to Section 1</a></li>
    <li><a href="#section2">Go to Section 2</a></li>
    <li><a href="#section3">Go to Section 3</a></li>
  </ul>

  <h2 id="section1">Section 1</h2>
  <p>This is the content of Section 1.</p>

  <h2 id="section2">Section 2</h2>
  <p>This is the content of Section 2.</p>

  <h2 id="section3">Section 3</h2>
  <p>This is the content of Section 3.</p>

</body>
</html>

In this example, we have created a mini table of contents by setting up links that jump to specific sections within the same page. We used the HTML id attribute with unique values to mark different sections of the page. Clicking on each link in the navigation menu scrolls the browser window to the specific section.

This approach not only enhances the user experience by making navigation smoother and more direct but also helps organize content, especially on long webpages.

Using HTML Id Attribute in JavaScript


HTML id attribute is extremely useful in JavaScript for accessing specific elements directly. We can use the id attribute in JavaScript to perform some tasks for that specific element. In JavaScript, we can access an element with a specific id using the getElementById() method.

Example 5:

<!DOCTYPE html>
<html>
<body>
   <button id="clickMe">Click me</button>

<script>
    document.getElementById('clickMe').addEventListener('click', function() {
     alert('Button Clicked!');
    });
</script>
</body>
</html>

In this example, JavaScript uses the id attribute to find the button and adds an event listener to it. When the button is clicked, a message is displayed.

Difference Between Class and ID in HTML


Multiple HTML elements can use the same class name, while one HTML element can only use an id name within the page. Look at the below code.

Example 6:

<!DOCTYPE html>
<html>
<head>
<style>
/* Style the element with the id "header" */
#header {
   background-color: red;
   color: white;
   padding: 30px;
   text-align: center;
}

/* Style all elements with the class name "favCity" */
.favCity {
    background-color: tomato;
    color: white;
    padding: 10px;
}
</style>
</head>
<body>
<!-- An element with a unique id -->
<h1 id="header">My Favorite Cities</h1>

<!-- Multiple elements with same class -->
<h2 class="favCity">Dhanbad</h2>
<p>Dhanbad is the coal capital of India.</p>

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

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

</body>
</html>

In this tutorial, we have explained the HTML id attribute, illustrating its use through various examples. We hope you now understand how to define an HTML element with a unique identifier using the id attribute.
Happy coding!!!

Please share your love