HTML Id Attributes

HTML Tutorial

HTML Forms

HTML Graphics

HTML Media

HTML API

HTML Id Attribute

The HTML id attribute specifies a unique id for an HTML element.

More than one element with the same id is not allowed in an HTML document

Using The id Attribute

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

The id attribute indicates a specific style declaration in a style sheet. It allows 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 {}.

Example:

				
					<style>
#myHeader {
  background-color: lightblue;
  color: black;
  padding: 40px;
  text-align: center;
} 
</style>

<p>Use CSS to style an element with the id "myHeader":</p>
<p id="myHeader">My Header</p>


				
			

Output:

Use CSS to style an element with the id “myHeader”:

My Header

Difference Between Class and ID

Multiple HTML elements can use the same class name, while an id name must only be used by one HTML element within the page

Example

				
					<style>
#myHeader {
  background-color: lightblue;
  color: black;
  padding: 40px;
  text-align: center;
}

/* Style all elements with the class name "city" */
.city {
  background-color: tomato;
  color: white;
  padding: 10px;
} 
</style>
<p id="myHeader">My Cities</p>
<!-- Multiple elements with same class -->
<p class="city">London</p>


				
			

Output:

My Cities

London

The id Attribute in JavaScript

JavaScript uses the id attribute to perform some tasks for that specific element.

JavaScript can access an element with a specific id with the getElementById() method:

Example

				
					<p>JavaScript can access an element with a specified id by using the getElementById() method:</p>
<p id="mHeader">Hello World!</p>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
  document.getElementById("mHeader").innerHTML = "Have a nice day!";
}
</script>



				
			

Output: