Movatterモバイル変換


[0]ホーム

URL:


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

Element: 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.

ThequerySelector() method of theElementinterface returns the first element that is a descendant of the element on which it isinvoked that matches the specified group of selectors.

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

The first descendant element ofbaseElement which matches the specifiedgroup ofselectors. The entire hierarchy of elements is considered whenmatching, including those outside the set of elements includingbaseElementand its descendants; in other words,selectors is first applied to thewhole document, not thebaseElement, to generate an initial list ofpotential elements. The resulting elements are then examined to see if they aredescendants ofbaseElement. The first match of those remaining elements isreturned by thequerySelector() method.

If no matches are found, the returned value isnull.

Exceptions

SyntaxErrorDOMException

Thrown if the specifiedselectors are invalid.

Examples

Let's consider a few examples.

Find a specific element with specific values of an attribute

In this first example, the first<style> element which either has notype or has type "text/css" in the HTML document body is returned:

js
const el = document.body.querySelector(  "style[type='text/css'], style:not([type])",);

Get direct descendants using the :scope pseudo-class

This example uses the:scope pseudo-class to retrieve direct children of theparentElement element.

HTML

html
<div>  <h6>Page Title</h6>  <div>    <span>Love is Kind.</span>    <span>      <span>Love is Patient.</span>    </span>    <span>      <span>Love is Selfless.</span>    </span>  </div></div>

CSS

css
span {  display: block;  margin-bottom: 5px;}.red span {  background-color: red;  padding: 5px;}

JavaScript

js
const parentElement = document.querySelector("#parent");let allChildren = parentElement.querySelectorAll(":scope > span");allChildren.forEach((item) => item.classList.add("red"));

Result

The entire hierarchy counts

This example demonstrates that the hierarchy of the entire document is considered whenapplyingselectors, so that levels outside the specifiedbaseElement are still considered when locating matches.

HTML

html
<div>  <h5>Original content</h5>  <p>    inside paragraph    <span>inside span</span>    inside paragraph  </p></div><div>  <h5>Output</h5>  <div></div></div>

JavaScript

js
const baseElement = document.querySelector("p");document.getElementById("output").textContent =  baseElement.querySelector("div span").textContent;

Result

The result looks like this:

Notice how the"div span" selector still successfully matches the<span> element, even though thebaseElement's child nodesdo not include the<div> element (it is still part of the specifiedselector).

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></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 container = document.querySelector("#container");const log = document.querySelector("#log");function random(number) {  return Math.floor(Math.random() * number);}function setBackgroundColor(id) {  log.textContent = "";  try {    const element = container.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.

More examples

SeeDocument.querySelector() for additional examples of the properformat for theselectors.

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp