HTML id Attribute

By IncludeHelp Last updated : October 13, 2024

The id Attribute

The id attribute is used to specify a unique id for an element in HTML. This id cannot be used for multiple elements in HTML. You can add the id to any HTML element.

The naming id attributes The id name is case-sensitive, the name must have one character and no whitespaces in two words (spaces, tabs, etc).

Using id Attribute

The id attribute can be used to reference the HTML tag in CSS and JavaScript to perform a certain transformation in an HTML tag that contains the id attribute. We use # followed by the name of the id attribute to refer to the element.

Referencing id Attribute in CSS

<!DOCTYPE html>
<html>
  <head>
    <style>
      #element {
      background-color: #f40;
      color: #fff;
      padding: 40px;
      text-align: center;
      }
    </style>
  </head>
  <body>
    <h1 id="element">Hello! This is an HTML element. </h1>
  </body>
</html>

Output

HTML The id attribute | Example 1

Referencing id Attribute in JavaScript

In JavaScript also, we can use the id attribute to reference an element and perform a specific task on it. document.getElementById() is used to reference an element using JavaScript.

<!DOCTYPE html>
<html>
  <body>
    <h1 id="greeting">Welcome Text</h1>
    <button onclick="displayResult()">Say Hello!</button>
    <script>
      function displayResult() {
          document.getElementById("greeting").innerHTML = "Hello! ";
      }
    </script>
  </body>
</html>

Output

HTML The id attribute | Example 2

After clicking on the "Say Hello!" button...

HTML The id attribute | Example 3

Uses of id in Webpage

ids of elements along with links are a great way for navigation to element on the same page which is so long.

Using the link to a specific id in the page will navigate us to that element in HTML.

We will see a separate example to do this.

Classes vs ID Attribute in HTML

In HTML, two elements are used to reference the HTML element. A class can be used to reference multiple HTML elements whereas id can be used to reference single HTML elements.

Read: Class attribute in HTML

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.