Movatterモバイル変換


[0]ホーム

URL:


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

Document: 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⁩.

TheDocument methodquerySelector()returns the firstElement within the document that matches the specifiedCSS selector, or group of CSS selectors. If no matches are found,null is returned.

The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.

If the specified selector matches an ID that is incorrectly used more than once in thedocument, the first element with that ID is returned.

CSS pseudo-elements will never return any elements.

Syntax

js
querySelector(selectors)

Parameters

selectors

A string containing one or more selectors to match. This stringmust be a valid CSS selector string; if it isn't, aSyntaxError exceptionis thrown.

Note that the HTML specification does not require attribute values to be valid CSS identifiers. If aclass orid attribute value is not a valid CSS identifier, then you must escape it before using it in a selector, either by callingCSS.escape() on the value, or using one of the techniques described inEscaping characters. SeeEscaping attribute values for an example.

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.

If you need a list of all elements matching the specified selectors, you should usequerySelectorAll() instead.

Exceptions

SyntaxErrorDOMException

Thrown if the syntax of the specifiedselectors is invalid.

Examples

Finding the first element matching a class

In this example, the first element in the document with the classmyclass is returned:

js
const el = document.querySelector(".myclass");

Complex selectors

Selectors can also be really powerful, as demonstrated in the following example. Here,the first<input> element with the name "login"(<input name="login"/>) located inside a<div> whoseclass is "user-panel main" (<div>) in thedocument is returned:

js
const el = document.querySelector("div.user-panel.main input[name='login']");

Negation

As all CSS selector strings are valid, you can also negate selectors:

js
const el = document.querySelector(  "div.user-panel:not(.main) input[name='login']",);

This will select an input with a parent div with theuser-panel class butnot themain class.

Escaping attribute values

This example shows that if an HTML document contains anid which is not a validCSS identifier, then we must escape the attribute value before using it inquerySelector().

HTML

In the following code, a<div> element has anid of"this?element", which is not a valid CSS identifier, because the"?" character is not allowed in CSS identifiers.

We also have three buttons, and a<pre> element for logging errors.

html
<div></div><button>No escape</button><button>CSS.escape()</button><button>Manual escape</button><pre></pre>

CSS

css
div {  background-color: blue;  margin: 1rem 0;  height: 100px;  width: 200px;}

JavaScript

All three buttons, when clicked, try to select the<div>, and then set its background color to a random value.

  • The first button uses the"this?element" value directly.
  • The second button escapes the value usingCSS.escape().
  • The third button explicitly escapes the"?" character using a backslash. Note that we must also escape the backslash itself, using another backslash, like:"\\?".
js
const log = document.querySelector("#log");function random(number) {  return Math.floor(Math.random() * number);}function setBackgroundColor(id) {  log.textContent = "";  try {    const element = document.querySelector(`#${id}`);    const randomColor = `rgb(${random(255)} ${random(255)} ${random(255)})`;    element.style.backgroundColor = randomColor;  } catch (e) {    log.textContent = e;  }}document.querySelector("#no-escape").addEventListener("click", () => {  setBackgroundColor("this?element");});document.querySelector("#css-escape").addEventListener("click", () => {  setBackgroundColor(CSS.escape("this?element"));});document.querySelector("#manual-escape").addEventListener("click", () => {  setBackgroundColor("this\\?element");});

Result

Clicking the first button gives an error, while the second and third buttons work properly.

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-2025 Movatter.jp