Search code examples
javascriptdom-events

Loop through input elements and get all ids that starts with 'value_'


var inputs = document.getElementsByTagName("input");
    
for (var i = 0; i < inputs.length; i++)
{
    if (document.getElementById("value_[0-9]"))
    {
        alert('found: ' + inputs[i].value);
    }
    else
    {
        alert(inputs[i].value);
    }
}

I'm using the condition to get only input IDs that starts with value_

if (document.getElementById("value_[0-9]"))

but nothing is true where I have 5 or more IDs in my form. i.e. value_1, value_2, value_3 etc..


Solution

  • Combine document.querySelectorAll with Array.prototype.slice to make it an Array

    Array.prototype.slice.call(document.querySelectorAll('input[id^="value_"]'));
    

    From here you can do your favorite loop, e.g. Array.prototype.forEach