HTML DOM querySelector() Method | javascript selector
ExamplesGetthefirst
element:document.querySelector("p");TryitYourself»[1]Getthefirstelementwithclass="example":document.querySelector(".example");TryitYourself»[2]Moreexamplesbelow.DefinitionandUsageThequerySelector()methodreturnsthefirstelementthatmatchesaCSSselector.Toreturnallmatches(notonlythefirst),usethequerySelectorAll()instead.BothquerySelector()andquerySelectorAll()throwaSYNTAX_ERRexceptioniftheselector(s)isinvalid.TheDifferenceBetweenanHTMLCollectionandaNodeListANodeListand...
ExamplesGet the first <p> element:
document.querySelector("p");
Try it Yourself »[1]Get the first element with class="example":
document.querySelector(".example");
Try it Yourself »[2]More examples below.
Definition and UsageThe 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.
The Difference Between an HTMLCollection and a NodeListA 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 collecti...