how to loop through getElementById with incremental id

Viewed 720

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?

3 Answers

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.

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 .

Related