HTML Attribute Class - Example
HTML Attribute class can be used on HTML elements, which can be used to apply CSS styles and apply Javascript actions.
Here is the example code, where we have tried to apply both Styles and Javascript actions as mentioned below.
- Applied CSS styles to heading elements using the head class, which applies a gray background color upon page load.
- Applied JavaScript actions on the heading elements using the highlight class, which highlights the text in red when the action is invoked.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.head {
background-color: gray;
}
</style>
</head>
<body>
<h1>HTML Class Attribute</h1>
<button onclick="highlightHeadings()">Highlight Headings</button>
<h2 class="head highlight">Heading One</h2>
<p class="para">Paragraph One text goes here.</p>
<h2 class="head highlight">Heading Two</h2>
<p class="para">Paragraph Two text goes here.</p>
<h2 class="head highlight">Heading Three</h2>
<p class="para">Paragraph Three text goes here.</p>
<script>
function highlightHeadings() {
var x = document.getElementsByClassName("highlight");
for (var i = 0; i < x.length; i++) {
x[i].style.color = "red";
}
}
</script>
</body>
</html>
Overall
This example helps us understand the use cases of the HTML class attribute.