HTML id Attribute Tutorial

  • Post author:
  • Post category:HTML

In this section, we will learn what the id attribute is and how to use it in HTML.

id Attribute in HTML

The id attribute is a way of uniquely identifying an HTML element in a document!

Using this attribute, we can assign a unique name to an HTML element and then use that name to access the element and run any necessary modification to the element using other languages like CSS and JavaScript.

For example, let’s say you have two paragraphs in your document and both are created using the HTML <p> element. Now, if you want to differentiate between these two paragraphs uniquely, you can set the id attribute for each one and assign a value to them. Now using this id attribute we can easily access each element.

HTML id Attribute Syntax:

<element-name id = “value”> </element-name>

The value we set for an id attribute must be unique! Meaning no other elements can have the same value for this attribute that we set for an element.

Example: using id attribute in HTML

See the Pen using id attribute in HTML by Omid Dehghan (@odchan1) on CodePen.

CSS for id

Using the id value, we can access the target element in CSS and apply any type of style to the target element.

Example: CSS by id

See the Pen CSS by id by Omid Dehghan (@odchan1) on CodePen.

Here the id attribute of the first paragraph is set to `firstp` and so we’ve used the value of this attribute in the CSS style section of the code to access this paragraph and finally changed its color to blue.

JavaScript and id Attribute

JavaScript language also has functions that allow us to access elements of an HTML document based on their id value!

For example, in JavaScript there’s a function called `getElementById()` where we put the value of an id attribute as the argument of this function and it will return a reference to that element on the page.

Example: using id attribute in JavaScript

See the Pen using id attribute in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Note: in the JavaScript tutorial section, we’ve covered the core of this language. So if you’re not familiar with this language, please check the related section.

Difference between id and class (id vs class)

The main difference between the id and class attributes is that:

  • The value we set for an id attribute must be unique in that we can’t use the same id value for another element’s id attribute on the same document.
  • But the value of a class attribute can be shared between other element’s class attribute! As a matter of fact, the purpose of having a class attribute is to group a bunch of elements by using the same name for their class attribute!

Leave a Reply