Movatterモバイル変換


[0]ホーム

URL:


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

Document: querySelectorAll() 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 methodquerySelectorAll()returns a static (not live)NodeList representing a list of thedocument's elements that match the specified group of selectors.

Syntax

js
querySelectorAll(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

A non-liveNodeList containing oneElement object foreach element that matches at least one of the specified selectors or an emptyNodeList in case of no matches. The elements are in document order — that is, parents before children, earlier siblings before later siblings.

Note:If the specifiedselectors include aCSS pseudo-element, the returned listis always empty.

Exceptions

SyntaxErrorDOMException

Thrown if the syntax of the specifiedselectors string is not valid.

Examples

Obtaining a list of matches

To obtain aNodeList of all of the<p> elements in thedocument:

js
const matches = document.querySelectorAll("p");

This example returns a list of all<div> elements within the documentwith a class of eithernote oralert:

js
const matches = document.querySelectorAll("div.note, div.alert");

Here, we get a list of<p> elements whose immediate parent elementis a<div> with the classhighlighted and which arelocated inside a container whose ID istest.

js
const container = document.querySelector("#test");const matches = container.querySelectorAll("div.highlighted > p");

This example uses anattribute selector to return a list of the<iframe> elements in thedocument that contain an attribute nameddata-src:

js
const matches = document.querySelectorAll("iframe[data-src]");

Here, an attribute selector is used to return a list of the list items contained withina list whose ID isuser-list which have adata-active attributewhose value is1:

js
const container = document.querySelector("#user-list");const matches = container.querySelectorAll("li[data-active='1']");

Accessing the matches

Once theNodeList of matching elements is returned, you can examine itjust like any array. If the array is empty (that is, itslength property is0), then no matches were found.

Otherwise, you can use standard array notation to access the contents of the list. Youcan use any common looping statement, such as:

js
const highlightedItems = userList.querySelectorAll(".highlighted");highlightedItems.forEach((userItem) => {  deleteUser(userItem);});

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 inquerySelectorAll().

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 elements = document.querySelectorAll(`#${id}`);    const randomColor = `rgb(${random(255)} ${random(255)} ${random(255)})`;    elements[0].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-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