const el = document.querySelector(".myclass");Document: querySelector() method / notebook
Document: querySelector() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const el = document.querySelector("div.user-panel.main input[name='login']");const el = document.querySelector(
"div.user-panel:not(.main) input[name='login']",
);<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>div {
background-color: blue;
margin: 1rem 0;
height: 100px;
width: 200px;
}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");
});