DocumentFragment: querySelector() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheDocumentFragment.querySelector() method returns thefirst element, ornull if no matches are found, within theDocumentFragment (using depth-first pre-order traversal of thedocument's nodes) that matches the specified group of selectors.
If the selector matches an ID and this ID is erroneously used several times in thedocument, it returns the first matching element.
If the selectors specified in parameter are invalid aDOMException withaSYNTAX_ERR value is raised.
In this article
Syntax
querySelector(selectors)Parameters
selectorsA string containing one or more CSS selectors separated bycommas.
Return value
AnElement object representing the first element in the documentthat matches the specified set ofCSS selectors, ornull is returned if there are no matches.
Examples
>Basic example
In this basic example, the first element in theDocumentFragment withthe classmyclass is returned:
const el = documentfragment.querySelector(".myclass");CSS syntax and the method's argument
The string argument pass toquerySelector must follow the CSS syntax. Tomatch ID or selectors that do not follow the CSS syntax (by using semicolon or spaceinappropriately for example), it's mandatory to escape the wrong character with adouble back slash:
<div></div><div></div>document.querySelector("#foo\bar"); // Does not match anythingdocument.querySelector("#foo\\\\bar"); // Match the first divdocument.querySelector("#foo:bar"); // Does not match anythingdocument.querySelector("#foo\\:bar"); // Match the second divSpecifications
| Specification |
|---|
| DOM> # ref-for-dom-parentnode-queryselector①> |
Browser compatibility
See also
- The
DocumentFragmentinterface it belongs to.