Search code examples
javascriptdominnerhtmlgetelementsbyclassname

Javascript - Passing from a DOM element to array


Hello and thank you for your time.

Here is the code :

<script>
var names = document.getElementsByClassName('xx');
var ar = [];
for (var i = 0, c = names.length ; i < c ; i++) {
ar[i] = names[i].innerHTML;
alert(ar[i]);// the results are : undefined
}
</script>`

I've tried to use the method tostring, or to push the results into the array but without success.

Thanks


Solution

  • Your main issue seems to be fixed. Make sure the DOM has been loaded before you try to run your code, and there is no need for two variables in your loop. Simplify it like below:

    window.onload = function () {
        var names = document.getElementsByClassName('xx');
        var ar = [];
    
        for (var i = 0 ; i < names.length ; i++) {
            ar[i] = names[i].innerHTML;
            alert(ar[i]);
        }
    };
    

    Fiddle