Reputation: 68
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?
Upvotes: 1
Views: 1967
Reputation: 1277
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
.
Upvotes: 4
Reputation: 3219
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
Upvotes: 1