The HTML class attribute is used to define a class for an HTML element.
The HTML class attribute is used to define a single or multiple class names for an HTML element.
These class name can be used by CSS and JavaScript to do some custom tasks for HTML elements.
We can use this class in CSS with a specific class, write a period (.) character inside html element starting tags.
<style>
tag.
) character.For creating the HTML class we firstly define style for HTML class using <style> tag inside the <head> section.
Example :
<head>
<style>
.river{
color: blue;
font-family: monospace;
background-color: aliceblue;
}
</style>
</head>
Understand the syntax of HTML Classes.
<tag class="className"> content </tag>
<!DOCTYPE html>
<html>
<head>
<style>
.river{
color: blue;
font-family: monospace;
background-color: aliceblue;
}
</style>
</head>
<body>
<h1 class="river">Ganga</h1>
<h2 class="river">Yamuna</h2>
<h3 class="river">Saraswati</h3>
<h4 class="river">Kaveri</h4>
</body>
</html>
Let's use a class name "Country" with CSS to style all elements.
<style>
.country{
background-color: orange;
color: white;
padding: 10px;
}
</style>
<h2 class="country">India</h2>
<p>India Mottos is Truth alone triumphs.</p>
<h2 class="country">Nepal</h2>
<p>Nepal Mottos is Mother and motherland are greater than heaven.</p>
<h2 class="country">South Africa</h2>
<p>South Africa Mottos is Diverse people unite or Unity in Diversity.</p>
<style>
.country{
background-color: orange;
color: white;
padding: 10px;
}
.india{
border:solid green 3px;
}
</style>
<h2 class="country india">India</h2>
<p>India Mottos is Truth alone triumphs.</p>
<h2 class="country">Nepal</h2>
<p>Nepal Mottos is Mother and motherland are greater than heaven.</p>
<h2 class="country">South Africa</h2>
<p>South Africa Mottos is Diverse people unite or Unity in Diversity.</p>
These class name used by JavaScript to do some custom tasks for HTML elements.
JavaScript can access elements with a specific class name with the getElementsByClassName()
method and we applied custom tasks on this element.
<script>
function myFunction() {
var x = document.getElementsByClassName("country");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>