natanel97 natanel97 - 25 days ago 7
Javascript Question

querySelectorAll loop "undefined"

I try to loop over few input elements in order to get each value, but for some reason I only get the last one:

<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>
<script>
function loop() {
var element = document.querySelectorAll('[data-loop="true"]');
for(var i = 0; i < element.length; i++) {
console.log(element[i].length);
// or:
// document.getElementById('output').innerHTML = element[i].value + '<br>';
}
}
</script>


The console shows
undefined
and when I try to output the values, I only get it from the last element and not from all of them. What am I doing wrong?

Thank you very much (and please excuse my english)

Answer

You are trying to get the length of the element itself:

console.log(element[i].length);

Elements don't have a length.

I suspect you are trying to get the length of the value of the elements:

console.log(element[i].value.length);

function loop() {
  
        // elements will be a "node list" containing any/all elements
        // that match the query.
        var elements = document.querySelectorAll('[data-loop="true"]');
      
        // Because it is a node list, which is an array-like object,
        // it has a "length" property:
        console.log("There were " + elements.length + " elements found.");
      
        // ...And, it can be looped through
        for(var i = 0; i < elements.length; i++) {
            // It's contained elements are indexed and when you do that,
            // you may access properties of the elements themselves
            console.log(elements[i].value);
            // or:
            document.getElementById('output').innerHTML += elements[i].value + '<br>';
        }
    }
<p>Type some text in the textboxes and then click the button:</p>
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>