MDN self-hosted library · e01.org

Document: querySelectorAll() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const matches = document.querySelectorAll("p");
js
const matches = document.querySelectorAll("div.note, div.alert");
js
const container = document.querySelector("#test");
const matches = container.querySelectorAll("div.highlighted > p");
js
const matches = document.querySelectorAll("iframe[data-src]");
js
const container = document.querySelector("#user-list");
const matches = container.querySelectorAll("li[data-active='1']");
js
const highlightedItems = userList.querySelectorAll(".highlighted");

highlightedItems.forEach((userItem) => {
  deleteUser(userItem);
});
html
<div id="this?element"></div>

<button id="no-escape">No escape</button>
<button id="css-escape">CSS.escape()</button>
<button id="manual-escape">Manual escape</button>

<pre id="log"></pre>
css
div {
  background-color: blue;
  margin: 1rem 0;
  height: 100px;
  width: 200px;
}
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");
});