HTML ID


The ID attribute in HTML is used to specify a unique identity to an element within a document. It is like a pointer pointing to a batch of variables containing some values which can also be accessed by CSS and JavaScript to be read and manipulated further. Value of the id attribute must be unique within HTML document.

The value of the Id attribute is case sensitive and can also be used to create HTML bookmarks.

The ID attribute is defined using the # symbol followed by id name then the properties are defined with {} brackets.


For example:


<!DOCTYPE html>
<html>
<head>
<title> Id Attribute </title>
<style>
#myformat {
  text-align: center;
  background-color: SaddleBrown;
  font-size: 30px;
  color: white;
}
</style>
</head>
<body>

<div id="myformat">
This is a document for HTML IDs
</div>

</body>
</html>

Live Demo!


Output:
This is a document for HTML IDs


In the above example, #myformat is the id name, which is called in the div tag in the body, hence, accessing all the format specifications with one word only.


USE OF THE Id ATTRIBUTE IN JAVASCRIPT


Id attribute is used by JavaScript to access that specific element and perform some tasks for it by using getElementId() method.


Something like this:


<script>
function result() {
document.getElementById("myformat").innerHTML =
 "main document format";
}
result();
</script>

Live Demo!


Difference between HTML id and class


Some beginners get confused between using HTML class and id attributes, as both can be used to access elements.

Remember that an element can only have one ID which must be unique. Classes can be applied to multiple elements and also combined.


For example:


<!DOCTYPE html>
<html>
<head>
<style>
#tree {
  background-color: Teal;
  color: white;
  padding: 5px;
  text-align: center;
}
.fruit {
  background-color: Aquamarine;
  color: black;
  padding: 3px;
} 
</style>
</head>
<body>

<h1>Difference Between Class and ID</h1>
<p>A class name can be used by multiple HTML
elements, while an id name must only be used
by one HTML element within
the page:</p>

<!-- An element with a unique id -->
<h1 id="tree">My Trees</h1>

<!-- Multiple elements with same class -->
<h2 class="fruit">Mango</h2>
<p>Mango is the king of fruits.</p>

<h2 class="fruit">Papaya</h2>
<p>Papaya is good for digestion.</p>

<h2 class="fruit">Pineapple</h2>
<p>Pineapple tastes better when grilled.</p>

</body>
</html>

Live Demo!


Output:

Difference Between Class and ID

A class name can be used by multiple HTML elements, while an id name must only be used by one HTML element within the page:

My Trees

Mango

Mango is the king of fruits.

Papaya

Papaya is good for digestion.

Pineapple

Pineapple tastes better when grilled.



Some beginners get confused between using HTML class and id attributes, as both can be used to access elements.
Remember that an element can only have one ID which must be unique. Classes can be applied to multiple elements and also combined.