2

Find all DOM elements which ID contains a string, but I want to use vanillaJS. I know that in here there is a solution using jQuery, but in this case, I want to use only pure javascript.

I know that with this :

document.querySelectorAll("[id='parteOfanID']")

We can get all elements which as the attribute id with the value "parteOfanID".

Thank you

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130

2 Answers2

4

You could use *= with the attribut selector [] like :

document.querySelectorAll('[id*="string_here"]')

console.log(document.querySelectorAll('[id*="identifier_"]').length);
<span id="test"></span>
<span id="identifier_1"></span>
<span id="identifier_2"></span>
<span id="identifier_3"></span>
<span id="test"></span>
<span id="identifier_4"></span>
<span id="test"></span>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
3

Use document.querySelectorAll() that gets a CSS selector (like jQuery) and returns NodeList:

var elements = document.querySelectorAll('[id*="some text"]');
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77