MakeW3web

HTML id Attribute

The HTML `id` attribute is used to assign a unique identifier to an HTML element. The `id` attribute is primarily used for:

  1. Styling elements using CSS: Although it's more common to use classes for styling purposes, you can also use the `id` attribute to apply styles to a specific element.
  2. Manipulating elements using JavaScript: The `id` attribute makes it easy to select and modify a specific element using JavaScript, especially with the `getElementById()` method.
It is important to note that each `id` value must be unique within an HTML document, and an element can have only one `idattribute.
Here's an example of how to use the `id` attribute in HTML and style the element using CSS:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ID Attribute Example</title>
  <style>
    #unique-heading {
      color: blue;
      font-size: 32px;
    }
  </style>
</head>
<body>
  <h1 id="unique-heading">This heading has the "unique-heading" ID.</h1>
  <p>Some text in a paragraph.</p>
  <p>Another paragraph with some text.</p>
</body>
</html>

In this example, we have created a CSS rule targeting the `#unique-heading` ID. The CSS rule sets the text color to blue and the font size to 32 pixels. We then use the `id` attribute to apply this ID to the `<h1>` element in the HTML document.

In summary, the `id` attribute in HTML is used to assign a unique identifier to an element, which can be useful for applying styles using CSS or manipulating elements using JavaScript. Remember that each `id` value must be unique within an HTML document, and an element can have only one `id` attribute.

Was this page helpful?