HTML Class

HTML class is used to identify one or more class names for an HTML element. HTML class name can be used on any HTML element. You can use the class name in CSS and JavaScript to perform certain tasks for elements with the specified class name.

Example:

<!DOCTYPE html>
<html>
<head>
<title> Page Title </title>
</head>
<body>
<h1> This is class attribute example. </h1>
<h1 class="similar"> class attribute </h1>
</body>
</html>

Run Example

CSS with Class

In CSS to select the id of an element write a dot(.) character before the class name.

Example:

<style>
.class_name {
  color: red;
  background-color: lightblue;
  padding: 20px;
}

</style>

Run Example

Use Same Class Name

You can use same class name for the multiple elements if you want to use similar design for the elements.

Example:

<div class="country">
<h2>USA </h2>
<p>USA is a beautiful country. </p>
</div>
<div class="country">
<h2>Australia </h2>
<p>Australia is a beautiful country. </p>
</div>
<div class="country">
<h2>China </h2>
<p>China is a beautiful country. </p>
</div>

Run Example

Using Multiple Class Name

You can use multiple class name for a single element. Multiple class name must be separated by a space.

Example:

<div class="country">
<h2>USA </h2>
<p>USA is a beautiful country. </p>
</div>
<div class="country continent">
<h2>Australia </h2>
<p>Australia is a beautiful country. </p>
</div>
<div class="country">
<h2>China </h2>
<p>China is a beautiful country. </p>
</div>

Run Example

JavaScript with Class

You can use class attribute in JavaScript by using the getElementsByClassName() method.

Example:

function jsFunction() {
var x = document.getElementsByClassName("country");
for (count = 0; count < 10; count++) {
x[i].style.display= "none";
}
}

Run Example