Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. DocumentFragment
  4. querySelector()

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.

Syntax

js
querySelector(selectors)

Parameters

selectors

A 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:

js
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:

html
<div></div><div></div>
js
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 div

Specifications

Specification
DOM
# ref-for-dom-parentnode-queryselector①

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp