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 element’s id 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>

Explanation:

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

HTML Class and HTML ID:

The HTML ID attribute is used to define a 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>

Explanation:

In the above example, “hello” is an id attribute applied to a single HTML element, while the “flowers” is a Class name 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>

Explanation:

In the above example, we are changing the text using HTML ID with Javascript.