You can select elements with a specific class inside a <div> using JavaScript DOM methods. This allows you to target only the matching elements within a particular container.
- Use querySelectorAll() to select all elements matching a CSS selector.
- Call querySelectorAll() on the <div> to limit the search to that container.
- Loop through the selected elements to access or modify them.
Approach: Using querySelectorAll()
The querySelectorAll() method returns all elements that match a specified CSS selector. First, select the <div> element and then use .querySelectorAll() with the required class selector.
Syntax:
element.querySelectorAll(".className");Example: Selects all elements with the example1 class inside the <div> and changes their background color when the button is clicked.
<!DOCTYPE html>
<html>
<head>
<style>
#tag {
border: 4px solid black;
margin: 5px;
padding: 10px;
}
</style>
</head>
<body>
<div id="tag">
<p class="example1">HTML</p>
<p class="example1">CSS</p>
<p class="example1">JavaScript</p>
<p class="example2">C</p>
</div>
<br>
<button onclick="changeColor()">
Click to Apply Change
</button>
<script>
function changeColor() {
const elements = document
.getElementById("tag")
.querySelectorAll(".example1");
elements.forEach(function (element) {
element.style.backgroundColor = "blue";
});
}
</script>
</body>
</html>
After clicking the Click to Apply Change button, the elements containing HTML, CSS, and JavaScript have their background color changed, while the element containing C remains unchanged.
Output:
