Home > Blockchain >  Get dynamic elements by the middle/End of it's class name
Get dynamic elements by the middle/End of it's class name

Time:05-29

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:

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

  • Related