How to Use querySelectorAll in JavaScript for Multiple Element Selection?
The querySelectorAll
method in JavaScript allows you to select multiple elements from the DOM using CSS selectors. It returns a collection (NodeList) of all elements that match the specified selector.
<script>var paragraphs = document.querySelectorAll(".content");</script>
How to Use querySelectorAll in JavaScript for Multiple Element Selection
<!DOCTYPE html>
<html>
<head>
<title>Using querySelectorAll in JavaScript</title>
</head>
<body>
<h2>Title</h2>
<p class="content">Paragraph 1</p>
<p class="content">Paragraph 2</p>
<script>
// Select all paragraph elements with class "content"
var paragraphs = document.querySelectorAll(".content");
// Iterate through the collection of selected elements
paragraphs.forEach(function(paragraph) {
// Change the text content of each paragraph
paragraph.textContent = "New Text";
});
</script>
</body>
</html>
Code Output
Title
Paragraph 1
Paragraph 2