class attribute in Html:
class attribute in Html:
Here class in HTML is the most important attribute; the same class can be shared in multiple elements.
In HTML generally, the class attribute is used to point class name in the respective style sheet. You can manipulate more than one element having the same class name using CSS. The class name is also very beneficial as well used by JS and to alter the elements in HTML.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: yellow;
color: black;
margin: 10px;
}
</style>
</head>
<body>
<div class="city">
<h2>Madhya Pradesh</h2>
<p>Bhopal is the capital of Madhya pradesh.</p>
</div>
<div class="city">
<h2>India</h2>
<p>Delhi is the capital of India.</p>
</div>
<div class="city">
<h2>Uttarpradesh</h2>
<p>lucknow is the capital of Uttarpradesh.</p>
</div>
</body>
</html>
Note:
Here class name is case sensitive and the attribute class can be used on any HTML elements.
Syntax:
To access the class use the dot operator followed by the class name. With the help of this, we are using CSS to access the elements.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: yellow;
}
</style>
</head>
<body>
<div class="city">
<h2>Madhya Pradesh</h2>
</div>
<div class="city">
<h2>India</h2>
</div>
<div class="city">
<h2>Uttarpradesh</h2>
</div>
</body>
</html>
More than one class:
In HTML elements can belong to more than one class and to make the class different, you need to change the attribute value in it. To define multiple classes, you need to separate the name of the class with space.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: Black;
padding: 10px;
}
.main {
text-align: center;
}
</style>
</head>
<body>
<p>Here, you will learn new stuff that class attribute with space can be accessed by another way.</p>
<h2 class="city main">MP</h2>
<h2 class="city">Delhi</h2>
<h2 class="city">Uttarpradesh</h2>
</body>
</html>
How can we use JavaScript using class attributes?
Below is the example which tells how to link JS with class.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>In this example you will learn how to connect class with js</h2>
<p>You need to click on the button </p>
<button onclick="myFunction()">Hide elements</button>
<h2 class="city">MP</h2>
<p>bhopal is the capital of mp.</p>
<h2 class="city">India</h2>
<p>delhi is the capital of india.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the 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>
