Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript document.getElementsByClassName returning undefined

I have a function which should be fairly straightforward and is supposed to be done after loading in order to reduce initial load time.

Basically I am using this code to get all of the elements with class "prefImg" and do some stuff with them. But when debugging in firebug, it says that the var divsList is undefined.

function populatePrefsList()
    {
        var divsList = new Array();
        divsList = document.getElementsByClassName("prefImg");
        var x = divsList.length;
        var i = 0;
        for(i=0; i<divsList.length; i++) {
            var imgs = divsList[i].getElementsByTagName("img");
            var imgSRC = imgs[0].src;
            var alt = imgs[0].alt;
            var descs = divsList[i].getElementsByTagName("h4");
            var desc = descs[0].innerHTML;
            //var thisPref = new preference(imgSRC, alt, desc);
            //prefsList[i] = thisPref;
        }
    }

Obviously I have the breakpoint on var x = divsList.length...

I cannot understand this, I initially had the script in the Head of the page, but figuring it may have not loaded the divs yet, have moved it to the bottom of the Body. This did not solve it.

I have had var divsList = document.getElementsByClassName("prefImg");

If anyone could tell me where I have gone wrong then I would be grateful. There are about 50 divs with the className prefImg.

Cheers

like image 299
Ryan Durrant Avatar asked Jun 27 '12 21:06

Ryan Durrant


2 Answers

You can use querySelectorAll instead of getElementsByClassName:

change divsList = document.getElementsByClassName("prefImg");

to this divsList = document.querySelectorAll(".prefImg");

DEMO - http://jsfiddle.net/ya3gU/

BTW, you do not need to declare the array divsList before you set it. Just do:

var divsList = document.querySelectorAll(".prefImg");
like image 92
xcopy Avatar answered Sep 18 '22 10:09

xcopy


do not write this code in the head.. because this means the body did not load yet. do it in the end of your body tag or use-

window.addEventListener("load", function() { // code here });

like image 43
Erez Avidan Avatar answered Sep 19 '22 10:09

Erez Avidan