0

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)?

Dan
  • 3,647
  • 5
  • 20
  • 26
Jimmy J.K.
  • 25
  • 6
  • Please provide either a better description or preferably real failing/succeeding example code. Anyway the OP should be able to find a solution just by reading about e.g. [Attribute selectors syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#syntax) – Peter Seliger May 28 '22 at 13:23

1 Answers1

2
  1. The correct syntax is $= to find a class that ends with a particular string.
  2. 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>
Andy
  • 61,948
  • 13
  • 68
  • 95