[Solved] Loop through ID starting with speciific string [closed]


You can do it with document.querySelectorAll() and with for loop like follows:

var nodes = document.querySelectorAll('[id^=name_]');

for(var i = 0; i < nodes.length; i++)
{
    console.log(nodes[i].innerHTML);
}
<div id="name_a">aaa</div>
<div id="name_b">bbb</div>

Please note: with nodes.forEach you will get an exeption

“Uncaught TypeError: nodes.forEach is not a function”

because nodes is a NodeList and not an Array.

But if you want use Array.forEach() then you have to cast NodeList into Array like in following example:

var nodes = document.querySelectorAll('[id^=name_]');

[].forEach.call(nodes, function(elm)
{
    console.log(elm.innerHTML);
});
<div id="name_a">aaa</div>
<div id="name_b">bbb</div>

Please see documentation:

solved Loop through ID starting with speciific string [closed]