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)?
>Solution :
- 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 class="abc-123">Will be selected 1</div>
<div class="def-234">Will not be selected 1</div>
<div class="ghi-123">Will be selected 2</div>
<div class="jkl-234">Will not be selected 2</div>