How to use getElementsByClassName In Javascript
In this approach, we are using the getElementsByClassName method in JavaScript to filter <div> elements based on their class name. When a button is clicked, the function approach2Fn(className) displays only the <div> elements with the matching class name while hiding the others.
Example: The below example uses getElementsByClassName to filter a DIV element based on its class name using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Using getElementsByClassName</title>
<style>
.fruit {
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
width: 100px;
text-align: center;
}
.apple {
background-color: red;
color: white;
}
.banana {
background-color: yellow;
}
.orange {
background-color: orange;
color: white;
}
</style>
</head>
<body>
<h1 style="color: green;">w3wiki</h1>
<h3>Using getElementsByClassName</h3>
<button onclick="approach2Fn('apple')">
Apples
</button>
<button onclick="approach2Fn('banana')">
Bananas
</button>
<button onclick="approach2Fn('orange')">
Oranges
</button>
<div id="content">
<div class="fruit apple">Apple 1 </div>
<div class="fruit banana">Banana</div>
<div class="fruit orange">Orange</div>
<div class="fruit apple">Apple 2</div>
</div>
<script>
function approach2Fn(className) {
var divs = document.getElementsByClassName('fruit');
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.classList.contains(className)) {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
}
}
</script>
</body>
</html>
Output:
How to Filter a DIV Element Based on its Class Name using JavaScript?
Div Element can be filtered based on class name for displaying specific content using JavaScript. Here, we will explore two different approaches to filtering a DIV element.
Table of Content
- Using querySelectorAll and classList
- Using getElementsByClassName
Contact Us