The querySelector()
method returns the first element that matches a CSS selector.
To return all matches (not only the first), use the querySelectorAll()
instead.
Both querySelector()
and querySelectorAll()
throw a SYNTAX_ERR exception if the selector(s) is invalid.
A NodeList and an HTMLcollection is very much the same thing.
Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.
Both have a length property that returns the number of elements in the list (collection).
An HTMLCollection is a collection of document elements.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).
HTMLCollection items can be accessed by their name, id, or index number.
NodeList items can only be accessed by their index number.
An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
A NodeList is most often a static collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change.
The getElementsByClassName()
and getElementsByTagName()
methods return a live HTMLCollection.
The querySelectorAll()
method returns a static NodeList.
The childNodes
property returns a live NodeList.
Parameter | Description |
CSS selectors |
Required. One or more CSS selectors. CSS selectors select HTML elements based on id, classes, types, attributes, values of attributes etc. For a full list, go to our CSS Selectors Reference. For multiple selectors, separate each selector with a comma (See "More Examples"). |
Type | Description |
Object |
A NodeList with the first element that matches the CSS selector(s). If no matches are found, null is returned.
|
What's the simplest way to print a Java array?
How do I write a correct micro-benchmark in Java?
What is a raw type and why shouldn't we use it?
How can I fix 'android.os.NetworkOnMainThreadException'?
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
What is a NullPointerException, and how do I fix it?
How do I compare strings in Java?