HTML - Classes




HTML Classes

The class is an attribute which specifies one or more class names for an HTML element, the class attribute can be used on any HTML element, the class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name.

HTML class attribute is used to specify a single or multiple class names for an HTML element. The class name can be used by CSS and JavaScript to do some tasks for HTML elements.

You can use this class in CSS with a specific class, write a period (.) character, followed by the name of the class for selecting elements.

Example

<!DOCTYPE html>
<html>
<head>
<style>
.city {
	background-color: Tomato;
	color: DodgerBlue;
	padding: 7px;
}
</style>
</head>
<body>
<h2 class = "city">Chennai</h2>
<p>Chennai, on the Bay of Bengal in eastern India, is the capital of the state of Tamil Nadu. </p>
<h2 class = "city">Mumbai</h2>
<p>Mumbai (formerly called Bombay) is a densely populated city on India’s west coast.</p>
<h2 class = "city">Bengaluru</h2>
<p>Bengaluru (also called Bangalore) is the capital of India's southern Karnataka state.</p>
</body>

Result

Chennai

Chennai, on the Bay of Bengal in eastern India, is the capital of the state of Tamil Nadu.

Mumbai

Mumbai (formerly called Bombay) is a densely populated city on India’s west coast.

Bengaluru

Bengaluru (also called Bangalore) is the capital of India's southern Karnataka state.

Explanation − In the above example CSS styles all elements with the class name “city”.

Class Attribute in JavaScript

Example

<!DOCTYPE html>
<html>
<body>
<h2>Class Attribute in JavaScript</h2>
<p>Click the button, to hide all elements with the class name "city", with JavaScript:</p>
<button onclick="myFunction()">Hide elements</button>
<h2 class="city">India</h2>
<p>New Delhi, national capital of India.</p>
<h2 class="city">Srilankan</h2>
<p>Colombo, national capital of Srilankan.</p>
<h2 class="city">Japan</h2>
<p>Tokyo, national capital of Japan.</p>
<script>
function myFunction() {
  var x = document.getElementsByClassName("city");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
}
</script>
</body>
</html>

Result