I need to find a group of elements by the end of their class names, it's highly similar to this Get element by part of Name or ID however using document.querySelectorAll([class~=<constant string>])
does not work but [class=<full class name
including randoms chars (see below) does work.
The elements in question have a class name like. (random string of three chars)-(Some constant String) is it possible to find them by the (some constant string)?
CodePudding user response:
- The correct syntax is
$=
to find a class that ends with a particular string. - If you want to use a variable in that selector use a template string to insert it.
const constant = '123';
const divs = document.querySelectorAll(`[class$="${constant}"]`);
divs.forEach(div => console.log(div.textContent));
<div >Will be selected 1</div>
<div >Will not be selected 1</div>
<div >Will be selected 2</div>
<div >Will not be selected 2</div>