Introduction to querySelectorAll
JavaScript offers a variety of methods for selecting DOM elements, and among them, querySelectorAll
is one of the most powerful and versatile. This method allows you to select multiple elements that match a specific CSS selector. Unlike querySelector
, which only returns the first matching element, querySelectorAll
gives you a NodeList that includes all matches. This makes it very handy for bulk manipulations, such as replacing strings in multiple elements simultaneously.
This article will dive deep into how querySelectorAll
can be used in combination with the array method forEach
to replace strings efficiently within text nodes of selected elements. By the end, you will have a solid grasp of manipulating the DOM with JavaScript and enhancing your web application dynamically.
Whether you’re a beginner still finding your way in JavaScript or a seasoned developer looking for advanced techniques, this guide will help you understand both the basic usage and some innovative applications of these methods.
Using querySelectorAll
To get started, let’s look at how to use querySelectorAll
. The method accepts a selector string as its parameter. For instance, if you want to select all paragraphs in an HTML document, you would write:
const paragraphs = document.querySelectorAll('p');
This line retrieves all p
elements and stores them in a variable called paragraphs
. Since querySelectorAll
returns a NodeList, you can loop through each of these elements using forEach
.
Here’s how you can log the text content of each paragraph using forEach
:
paragraphs.forEach((para) => {
console.log(para.textContent);
});
This is the foundation for working with querySelectorAll
and forEach
, allowing you to manipulate the selected elements effectively.
Replacing Strings within Selected Elements
Now that we’ve covered how to retrieve elements with querySelectorAll
and loop through them with forEach
, let’s explore how to replace strings within these elements. For this example, assume you have multiple paragraphs of text and you want to replace all instances of the word