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?
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
.