Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

HTML Id Attribute

The HTML id attribute is used to specify a unique id for an HTML element.

You cannot have more than one element with the same id in an HTML document.


Using The Id Attribute

The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document.

The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.

The syntax for id is: write a hash character (#), followed by an id name. Then, define the CSS properties within curly braces {}.

In the following example we have an <h1> element that points to the id name "myHeader". This <h1> element will be styled according to the #myHeader style definition in the head section:

The HTML class attribute example:
<html>
<head>
<style>
#myheader {
background-color:skyblue;
color:black;
padding:40px;
text-align:center;
}
</style>
</head>
<body>
<h1 id="myheader">Soopro Pathshala</h1>
</body>
</html>


The id attribute in HTML is used to uniquely identify an element. Here are the key points:

1. Uniqueness

  • The id value must be unique within the document, meaning no two elements can share the same id.
  • Example: <div id="header"><div>. Only one element can have the id="header" in the same HTML document.

2. Used for styling

  • The id attribute can be used to apply specific styles to an element via CSS.
  • In CSS, #id is used to select an element by its id.

3. JavaScript Access

  • JavaScript uses the id attribute to interact with or manipulate an element.
  • The getElementById() method is commonly used to select elements by id.

4. Fragment Identifiers

  • The id attribute can be used in URLs to create fragment links (i.e., deep links) to specific sections of a webpage

5. Priority over classes in CSS

  • When an element has both an id and a class, the styles applied to the id have a higher specificity and will override the class styles if there's a conflict.

6. Accessibility and ARIA

  • The id attribute is often used in conjunction with ARIA (Accessible Rich Internet Applications) attributes to link elements, such as with aria-labelledby or aria-describedby.

7. Form Association

  • The id attribute is used to associate a label with a form input, where the label's for attribute matches the input’s id.

8. Case-Sensitivity

  • While HTML is not case-sensitive, the id value is case-sensitive when referenced in JavaScript, CSS, and URLs.

9. Best Practices

  • Use descriptive and meaningful id names to keep the code readable and maintainable.
  • Avoid using the same id across different elements, as it can cause issues with CSS and JavaScript functionality.