How to use querySelectorAll in Javascript

By FoxLearn 12/18/2024 7:36:15 AM   84
The `querySelectorAll` method in JavaScript is used to select multiple elements from the DOM based on a CSS selector. It returns a `NodeList` containing all the elements that match the specified selector.

You can use it with the `document` object to select elements on a webpage.

Here's an example of how you can use querySelectorAll:

// Select all the anchor tags on the webpage
const anchors = document.querySelectorAll('a');

// Loop through the selected anchor tags
anchors.forEach((element) => {
  // Do something with each selected element
  console.log(element.href);
});

In this example, querySelectorAll is used to select all the anchor tags (<a>) on the webpage. Then, a forEach loop is used to iterate through each selected anchor tag, logging the value of the href attribute to the console.