querySelectorAll() the best JavaScript function in the world!

Using querySelectorAll() with forEach()

The querySelectorAll() function is a method of the Document object in JavaScript that allows you to select a group of elements in a document based on a given CSS selector. It returns a NodeList object, which is a collection of nodes (elements) that can be accessed like an array.

The forEach() method is an array method that allows you to iterate over the elements in an array and perform a specific action on each element. It takes a callback function as an argument, which will be called for each element in the array with that element as its argument.

To use the forEach() method with the querySelectorAll() function, you can do the following:

document.querySelectorAll(cssSelector).forEach(callbackFunction);

Here's an example of how to use this combination to select all the p elements in a document and change their text color to red:

document.querySelectorAll('p').forEach(function(element) {
  element.style.color = 'red';
});

You can also use the forEach() method with a NodeList object obtained through other means, such as by calling the childNodes property of a parent element:

const parentElement = document.querySelector('#parent');
const childNodes = parentElement.childNodes;

childNodes.forEach(function(node) {
  console.log(node.nodeType);
});

In this example, the forEach() method is used to iterate over the child nodes of the element with the ID "parent", and the nodeType property of each node is logged to the console.

Note that the forEach() method is not supported in older browsers, so you may need to use a polyfill or a different technique to achieve the same behavior in those cases.