Vinod Sobale
Vinod Sobale

Reputation: 852

Diffrence between HTML collection & an Array in Javascript

Following code produces nothing but an error. I wish to retrieve REL attribute values of each of the DIVs. No idea, why I can'y do it.

Error I see in console: Uncaught TypeError: Object # has no method 'getAttribute'

    <div class="boxes">
        <div rel="first" class="box">Box 1</div>
        <div rel="second" class="box">Box 2</div>
        <div rel="third" class="box">Box 3</div>
    </div>
    <script>
        $(function(){
            var i = 0;
            var allDivs = document.getElementsByClassName('box');
            var arr = [];
            arr.push(allDivs);
            setInterval(function(){
                console.log(arr[i].getAttribute('rel'));
                i++;
            }, 1000);
        });
    </script>

Upvotes: 0

Views: 758

Answers (2)

Kapil gopinath
Kapil gopinath

Reputation: 1053

Replace the script with this:

     $(function(){
        var i = 0;
        var allDivs = document.getElementsByClassName('box');
        //allDivs itself is an array and there is no need to push the result to an array.

        setInterval(function(){
            console.log(allDivs[i].getAttribute('rel'));
            i++;
        }, 1000);

     });

Upvotes: 0

Levi
Levi

Reputation: 2113

you're pushing an array (NodeList to be exact) into an array and trying to get the attribute from the NodeList object instead of the individual elements. Try this:

<div class="boxes">
    <div rel="first" class="box">Box 1</div>
    <div rel="second" class="box">Box 2</div>
    <div rel="third" class="box">Box 3</div>
</div>
<script>
    $(function(){
        var i = 0;
        var allDivs = document.getElementsByClassName('box');
        var arr = [];
        arr.push(allDivs);
        setInterval(function(){
            console.log(arr[0][i].getAttribute('rel'));
            i++;
        }, 1000);
    });
</script>

By pushing the NodeList into the other array, you are essentially creating this:

var arr = [[<div element 1>, <div element 2>, <div element 3>]];

What you are probably wanting to do is to change your push line to:

arr.push.apply(arr, allDivs);

That will append all the individual elements inside the allDivs collection onto arr. Then you can access arr like you expected before: arr[i].getAttribute('rel') (arr's contents will be [<div element 1>, <div element 2>, <div element 3>];)

Upvotes: 1

Related Questions