Skip to main content

HTML Class Attribute

The HTML class property specifies the class of an HTML element.

The same class can be applied to several HTML elements.

Using The class Attribute

In a style sheet, the class attribute is frequently used to point to a class name. A JavaScript can also utilise it to access and manipulate items with the specified class name.

In the following example, there are three <div> components with the class attribute set to "city." According to the .city style specification in the head section, all three <div> components will be styled similarly:

<!DOCTYPE html>
.city {
background-color: grey;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
<div class="city">
<h2>New Delhi</h2>
<p>New Delhi is the capital of India.</p>

<div class="city">
<p>Moscow is the capital of Russia.</p>

<div class="city">
<p>Tokyo is the capital of Japan.</p>

The class attribute can be used on any HTML element.


The class name is case sensitive!

The Syntax For Class

To create a class, type a period (.) character followed by the name of the class. Then, within curly brackets, define the CSS properties.

Multiple Classes

HTML components can belong to several classes.

To specify several classes, use a space to separate the class names, such as <div class="city main">. All of the supplied classes will be used to style the element.

In the following example, the initial <h2> element belongs to both the city and the main classes and will receive CSS styles from both:

<h2 class="city main">New Delhi</h2>
<h2 class="city">Moscow</h2>
<h2 class="city">Tokyo</h2>

Different Elements Can Share Same Class

The same class name can be referenced by different HTML elements.

Both `<h2> and <p> in the following example point to the "city" class and will have the same style:

<h2 class="city">New Delhi</h2>
<p class="city">New Delhi is the capital of India</p>

Use of The class Attribute in JavaScript

JavaScript may also utilise the class name to do particular operations for certain items.

The getElementsByClassName() function in JavaScript allows you to get items with a given class name:


Click on a button to hide all elements with the class name "city":

function myFunction() {
var x = document.getElementsByClassName("city");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";