The document.querySelectorAll()
returns a list of DOM elements ( NodeList
) based on a CSS selector string.
The following code returns all of <div>
elements in the document:
var divs = document.querySelectorAll('div');
Code language: JavaScript (javascript)
The following code returns all <div>
elements with a class error
or warning
:
let divs = document.querySelectorAll("div.error, div.warning");
Code language: JavaScript (javascript)
See the following HTML snippet:
<div id="container">
<p class="note">This is a note</p>
<p class="note">This is another note</p>
<p class="error">An error message</p>
<div>
Code language: HTML, XML (xml)
The following gets a list of p
elements the class note
which are located inside another div
whose id is container
.
let container = document.querySelector("#container");
let matches = container.querySelectorAll("p.note");
Code language: JavaScript (javascript)
Once you find the matches, you can process it like an array. If the array is empty, then no matches were found.
The following code deletes all the <p>
element with the class note
found in the previous example:
matches.forEach(function(match) {
match.parentNode.removeChild(match);
});
Code language: PHP (php)
Was this tutorial helpful ?