HTML id Attribute


In HTML, the id attribute is used to uniquely identify an HTML element on a page. Unlike the class attribute, which can be applied to multiple elements, the `id` attribute should be unique within the HTML document. The purpose of the id attribute is to provide a way to select and manipulate a specific element using JavaScript or to create links to specific sections within a page.

This is an illustration of the use of the {id} attribute:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Id Attribute Example</title>
  <style>
    /* CSS styling for illustration purposes */
    #uniqueElement {
      color: blue;
      font-weight: bold;
    }
  </style>
</head>
<body>

<p id="uniqueElement">This paragraph has a unique ID.</p>

</body>
</html>

In this example:

  • The <p> element has the id="uniqueElement" attribute, making it uniquely identifiable within the document. 
  • The CSS styles are applied to the element with the `id` of "uniqueElement," making its text blue and bold.

Using the id attribute is especially common when working with JavaScript to interact with specific elements. For instance, you can use the document.getElementById() method to select and manipulate an element by its id

var paragraph = document.getElementById("uniqueElement");
paragraph.innerHTML = "This text has been changed using JavaScript!";

Additionally, the id attribute is often used in creating anchor links to specific sections within a page. For example:

<a href="#uniqueElement">Go to Unique Element</a>

This link would navigate to the element with the id of "uniqueElement" when clicked.

Remember that while the class attribute is used for applying styles or functionality to multiple elements, the id attribute is reserved for uniquely identifying a single element on a page. Each id value must be unique within the entire HTML document.

Post a Comment

Previous Post Next Post

Popular Items