Locating DOM elements using selectors
The Selectors API provides methods that make it quick and easy to retrieve
Returns the first matching
Elementnode within the node's subtree. If no matching node is found,
NodeListcontaining all matching
Elementnodes within the node's subtree, or an empty
NodeListif no matches are found.
NodeList returned by
querySelectorAll() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.
Only elements can be selected, so pseudo-classes are not supported.
To select all paragraph (
p) elements in a document whose classes include
note, you can do the following:
const special = document.querySelectorAll("p.warning, p.note");
You can also query by ID. For example:
const el = document.querySelector("#main, #basic, #exclamation");
After executing the above code,
el contains the first element in the document whose ID is one of