Categories
HTML Web development

HTML id

In one of the previous posts, we were talking about the HTML class attribute which defines equal styles of elements, today we’ll focus on the second very important attribute which defines HTML element – HTML id.

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).The id attribute can be used on any HTML element.

The id value can be used by CSS and JavaScript to perform certain tasks for the element with the specific id value.

In CSS, to select an element with a specific id, write a hash (#) character, followed by the id of the element:

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#header {
  background-color: pink;
  color: white;
  padding: 40px;
  text-align: center;
} 
</style>
</head>
<body>

<h1 id="header">Header</h1>

</body>
</html>

Output:

Difference Between Class and ID:

An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements:

<!DOCTYPE html>
<html>
<head>
<style>
/* Style the element with the id "myHeader" */
#header {
  background-color: pink;
  color: white;
  padding: 40px;
  text-align: center;
}

/* Style all elements with the class name "city" */
.city {
  background-color: green;
  color: white;
  padding: 10px;
} 
</style>
</head>
<body>

<h2>Difference Between Class and ID</h2>

<!-- A unique element -->
<h1 id="header">The Capitals</h1>

<!-- Multiple similar elements -->
<h2 class="city">Brussels</h2>
<p>Brussels is the capital of Belgium.</p>

<h2 class="city">Madrid</h2>
<p>Madrid is the capital of Spain.</p>

<h2 class="city">Lisbon</h2>
<p>Lisbon is the capital of Portugal.</p>

</body>
</html>

Output:

Using The id Attribute in JavaScript:

JavaScript can access an element with a specified id by using the getElementById method (you can ready more about this method here):

<!DOCTYPE html>
<html>
<body>

<h1 id="header">Hello World!</h1>
<button onclick="displayResult()">Change text</button>

<script>
function displayResult() {
  document.getElementById("header").innerHTML = "Have a nice day!";
}
</script>

</body>
</html>

Output:

Enjoy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *