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
  • 16,827
  • 6
  • 33
  • 48
Eidern
  • 68
  • 10

2 Answers2

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
  • 1,129
  • 2
  • 16
  • 30
  • This is more hacky. Since if you had an id somewhere in the app with "action_B" this would also be included in your result – Sweet Chilly Philly Jan 23 '21 at 21:45
  • 1
    Sure! But no any mentions about another thing than an index in the question. – Pierre Jan 23 '21 at 21:51
  • thanks, yes there are only indexes in my case; Could you explain a little more to me the expressions within this query? I don't understand it really well, and i don't know how to find the length of its answer – Eidern Jan 24 '21 at 09:08
  • 1
    I've just edit my answer with some extra examples and docs. – Pierre Jan 24 '21 at 09:43
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
  • 3,014
  • 2
  • 27
  • 37
  • 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