querySelectorAll in JavaScript DOM (Live Playground)
In this tutorial, we will learn how to use the querySelectorAll
method in JavaScript to select and manipulate multiple HTML elements using CSS selectors. We'll cover the basics of the method and provide sample code with explanations.
What is querySelectorAll?
The querySelectorAll
method is a built-in JavaScript DOM method that allows you to select all HTML elements that match a specified CSS selector. The method returns a static NodeList
of all elements that match the selector, or an empty NodeList if no matching elements are found. It enables you to access multiple elements in your HTML document using more complex and powerful selection criteria than other DOM selection methods.
Sample Code: Using querySelectorAll
Let's say we have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>
</body>
</html>
To use querySelectorAll
to select elements, you'll need to include a JavaScript <script>
tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.
Here's how you can select all p
elements with the class mainParagraph
and change their text content:
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>
<script>
// Select all elements with the class "mainParagraph"
var mainParagraphs = document.querySelectorAll('.mainParagraph');
// Loop through the NodeList and change the text content of each element
for (var i = 0; i < mainParagraphs.length; i++) {
mainParagraphs[i].textContent = 'This paragraph has been updated.';
}
</script>
</body>
</html>
After running this code, the text content of all p
elements with the class mainParagraph
will be updated to "This paragraph has been updated.".
Conclusion
The querySelectorAll
method is a powerful and versatile way to select and manipulate multiple HTML elements using CSS selectors. By mastering this method, you can easily access and modify specific elements in your HTML documents using more complex selection criteria, allowing you to create dynamic and interactive web pages.