1

I've got a webpage that got multiple ids like "action_1", "action_2", and so on.. I'dl like to loop through all these ids with a document.getElementById('action_'+i)

but as the pages got some variants, the i index is unknown . how should i loop for all the action_x ids?

Progman
  • 14,690
  • 4
  • 32
  • 46
Eidern
  • 58
  • 8

3 Answers3

4

You can use querySelector instead of getElementById:

document.querySelector('[id^="action_"]')

With the same selector and querySelectorAll (to loop over each actions):

document.querySelectorAll('[id^="action_"]').forEach(function(action) {
  console.log(action);
});

The selector [id^="action_"] mean : each id attribute (whatever html tag), starting with "action_".

Learn more about attribute selectors here, and here for querySelectorAll.

Pierre Arnissolle
  • 838
  • 2
  • 13
  • 26
1

This approach isn't entirely correct.

You would instead put a class onto your actions alongside their ID's.

<div class="actions"> </div>

then you can use the getElementsByClassName():

https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

This will give you all your elements in an HTML collection which you then need to loop over.

this post will help you loop an HTML collection: For loop for HTMLCollection elements

Sweet Chilly Philly
  • 2,499
  • 2
  • 26
  • 33
  • I'm agree with that, but i'm not looping through MY Webpage. It's someone else design that i cannot touch, i'm just injecting javascript in an already done webpage. – Eidern Jan 23 '21 at 21:46
  • either approach is correct :). you can loop in javascript, definitly not in any other langugage – Sweet Chilly Philly Jan 23 '21 at 21:48
-1

Modifying the answer of @parnissolle :

for(var i = 0; i< document.querySelector('[id^=action_]').length; i++) {
    document.getElementById('action_'+i);
}

That doesn't matter if there is action_B or smth like that, because we will only get the elements with the id structure of 'action_'+i .