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!
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.
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!