0

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>

2 Answers 2

1

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>];)

2
  • 2
    .getElementsByClassName does not return an Array. Instead, it returns a NodeList. Commented Dec 31, 2012 at 4:52
  • thanks for the distinction. it is important to know that the return value from getElementsByClassName is not a javascript Array, but a live collection, called a NodeList. I've updated my answer to be more clear.
    – Levi
    Commented Dec 31, 2012 at 5:03
0

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);

     });

Not the answer you're looking for? Browse other questions tagged or ask your own question.