What does the class attribute do?
The class attribute is used to assign an element one or more class names, which can be used to:
- apply styles in CSS,
- reference elements from JavaScript,
- group similar elements for shared actions or styling.
1. Main purpose
class lets you combine elements into logical groups and apply common properties to them.
Example:
<p class="note">This is an important note.</p>
<p class="note">Another note.</p>Now the same style can be applied to both elements.
2. Use in CSS
To style a class, a dot . is placed before the name:
.note {
color: darkblue;
font-style: italic;
}All elements with class="note" will be styled the same way.
3. Several classes on one element
You can assign several classes, separated by a space:
<p class="note warning">Be careful!</p>In this case, all the styles apply to the element:
.note { font-style: italic; }
.warning { color: red; }4. Use in JavaScript
JavaScript lets you find and change elements by class name:
<p class="highlight">Text</p>
<script>
const elements = document.getElementsByClassName("highlight");
elements[0].style.background = "yellow";
</script>This lets you change the styling of all elements of a given class at once.
5. Difference from id
| Property | id | class |
|---|---|---|
| Uniqueness | Only one element with that name | Can be on many elements |
| CSS selector | #header | .header |
| Use | For targeted configuration | For grouping and bulk styling |
Summary:
| Characteristic | Description |
|---|---|
| Purpose | Combines elements into groups |
| Where it's used | In CSS and JavaScript |
| Syntax | class="name" |
| Can you specify several | Yes, separated by a space |
Difference from id | Not unique, can be applied to many elements |
In simple terms:
class is a label for a group of elements.
It's needed to style, find, and manage several elements at once in the same way.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.