Skip to main content

What does the class attribute do?

Suggest an edit

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:

html
<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:

css
.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:

html
<p class="note warning">Be careful!</p>

In this case, all the styles apply to the element:

css
.note { font-style: italic; } .warning { color: red; }

4. Use in JavaScript

JavaScript lets you find and change elements by class name:

html
<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

Propertyidclass
UniquenessOnly one element with that nameCan be on many elements
CSS selector#header.header
UseFor targeted configurationFor grouping and bulk styling

Summary:

CharacteristicDescription
PurposeCombines elements into groups
Where it's usedIn CSS and JavaScript
Syntaxclass="name"
Can you specify severalYes, separated by a space
Difference from idNot 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Suggest an edit