What is the difference between class and id in HTML, CSS and JavaScript
What is the difference between class and id attributes? That kind of question is quite common in technical interviews for Front-end developers, especially for beginners.
Both class and id are HTML attributes that can be assigned to any HTML tag. They can be used and manipulated in HTML, CSS, and JavaScript.
- Difference between class and id in HTML
- Difference betweenclass and id in CSS
- Difference between class and id JavaScript
Difference between class and id in HTML
Each HTML element can have an id and a class attribute, however, the differences are:
- The id’s value must be unique in the whole document. As for the class, the value can be the same for multiple elements.
- The id’s value must not contain whitespace (spaces, tabs, etc.), while the class attribute allows space-separated values
<h1 id="main-heading" class="text heading-text">Main heading</h1>
<p class="text">Some text</p>
NOTE: both class and id can contain letters, numbers, dashes, and underscores, but the first character should always be a letter.
Difference between class and id in CSS
In CSS the minor difference between class and id is that they have special characters preceding the name. For id, it is pound ”#” for class it is period ”.”:
#main-heading {
font-size: 45px;
}
.text {
color: #333;
}
The main difference between class and id in CSS is that they have different selector specificity. The id has a higher specificity than a class.
E.g. looking at the following code, the id selector will override the class selector styles, even if the class selector is cascading after the id selector.
#main-heading {
color: #000;
}
.text {
color: #333;
}
It is considered a good practice to use classes to style elements, not the ids. One of the reasons for this, that it is easier to override a class selector than an id.
Difference between class and id in JavaScript
There’s not much difference between id and class in JavaScript. They are mostly used to select DOM elements and to access their values.
In JavaScript, you can select elements by their class name or by id. There are different ways how you can utilize classes and id to select DOM elements.
To select the element by id you can use:
document.getElementById('elementId')
method;document.querySelector('#elementId')
method;window.elementId or window['element-id']
if the id is using a dash.
To select the element by the class you can use:
document.querySelector('.elementClass')
method;document.getElementsByClassName('elementClass')
method;
To access the id attribute value of the element you can use the following approaches:
Element.id
- will output id stringelement.getAttribute('id')
- will output id string
To access the class value of the element you can use the following approaches:
Element.classList
- will output class stringelement.className
- will output class stringelement.getAttribute('class')
- will output class string