HTML Id attribute

A unique id is defined for an HTML element using the id attribute. It can be used on any HTML element. The value set to the Id attribute is case-sensitive. The value set to the Id attribute must contain at least one character. It also must not contain any whitespaces.

ID with CSS:

In CSS, a hash (#) character is used with the id of the element to select an HTML element with a specific id.
Example:

<!DOCTYPE html>
<html>
<head>
<style>
#hello {
  background-color: crimson;
  color: white;
  padding: 20px;
} 
</style>
</head>
<body>
<h1 id="hello">HELLO WORLD!!</h1>
</body>
</html>

Output:







HELLO WORLD!!

Explanation:
In the above example, “hello” is an id attribute which is used on an HTML element.

HTML Class and HTML ID:

The HTML ID attribute is used to define unique id that belongs to a single HTML element. The HTML class name on the other hand can be used by a single element as well as multiple elements.
Example:

<!DOCTYPE html>
<html>
<head>
<style>
#hello {
  background-color: black;
  color: white;
  padding: 20px;
} 
.flowers {
  background-color: crimson;
  color: white;
  padding: 15px;
} 
</style>
</head>
<body>
<h1 id="hello">Flowers</h1>
<h2 class="flowers">Rose</h2>
<h2 class="flowers">Lily</h2>
<h2 class="flowers">Orchid</h2>
</body>
</html>

Output:







Flowers

Rose

Lily

Orchid

Explanation:
In the above example, “hello” is an id attribute which is applied to a single HTML element, while the “flowers” is a Class name which is applied to multiple HTML elements.

HTML Id with Javascript:

The getElementById() method is used to get an element with a specified id by Javascript.
Example:

<!DOCTYPE html>
<html>
<body>
<h1 id="hello">Hello HTML!!</h1>
<button onclick="displayResult()">Text Change</button>
 
<script>
function displayResult() {
  document.getElementById("hello").innerHTML = "Hello, I am HTML!!";
}
</script>
</body>
</html>

Output:




Hello HTML!!

Explanation:
In the above example, we are changing the text using HTML Id with Javascript.

Please Share