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.
|
How to delete a newline if it is the last character in a file?
How to pass command-line arguments to a Perl program?
How to efficiently calculate a running standard deviation
Howto use a variable in the replacement side of the Perl substitution operator?
How to summ quickly all numbers in a file?
How to remove duplicate items from an array in Perl?
How to differ of Two Arrays Using Perl