HTML ID attribute

By | March 2, 2021

id attribute can be used with any HTML elements, and it can provide a unique id to different and similar elements.

ID attribute use

The ID attribute is generally used to specify unique id to an HTML element so it could be selected separately for styling and scripting. While mentioning the id attribute to an element, make sure that it has a unique value.

Vamware

CSS and JavaScript can select the element using its id value and provide corresponding styling and scripting. JavaScript contains methods which can select and manipulate the element values and styling using its id.

Example

<!DOCTYPE html>
<html>
<head>

<style>

 #first
 {
   color:red;
 }
</style>

</head>
<body>
    <p id ="first"> Welcome to TechGeekBuzz</p>
</body>
</html>

Output

Welcome to TechGeekBuzz

Here we have selected the <p> element using its id value "first"

Class vs ID

  • Class and ID can be used to serve the same purpose, but both are used in different scenarios.
  • Multiple elements can have the same class value, whereas every element id value must be unique.
  • While selecting the element by its id we use the # symbol followed by id value.
  • To select an element by its class we use the (.) period symbol followed by class name.

Example

<!DOCTYPE html>
<html>
<head>

<style>

#rank1{
color:red;
}

.first{
color: blue;
}

</style>

</head>
<body>
<h4 id ="rank1">Rank 1 </h4>
<p class= "first"> Name: Sam</p>
<p class= "first"> Age : 19 </p> 
</body>
</html>

Output

Rank 1

Name: Sam

Age : 19

ID as a bookmark

In webpages, bookmarks are created using id and anchor tag <a>. Using the bookmark the user can directly jump to a specific part of the web page. When there is a lot of content present on the webpage, bookmarks provide an alternative and fast way to jump on the specific section.

When the user clicks on the bookmark the page gets scrolled automatically and take the user to the specific section.

Example

<strong id ="FirstExample">  Example: </strong>
<a href ="#FirstExample"> First Example of the Page </a>

Output
First Example of the Page

ID Attribute in JavaScript

Like class, JavaScript also provides an event handler method called getElemetById()to select and manipulate the HTML element through its id value.

Example

<script>
x= document.getElementById("rank1");
alert(x.textContent)​;
</script>

Summary

  • id attribute can be used along with any HTML element.
  • In CSS to select an HTML element using its id, we need to use the # symbol followed by the id value.
  • Every element must have a unique id value.
  • id values are case sensitive.
  • id value at least has one character.

Leave a Reply

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