Bradley Hodges Bradley Hodges - 1 month ago 6
Javascript Question

"Cannot read property 'length' of undefined" - trying to get children of a classname

I'm trying to get all children of a classname (.select-options), and apply an

onclick
attribute. When I run the javascript, I get the following error:


Uncaught TypeError: Cannot read property 'length' of undefined


Here's my javascript:

function loadQuickAction() {
setTimeout(function() {
var x = document.getElementsByClassName("select-options").childNodes;
for(i=0; x<x.length; i++) {
x[i].setAttribute("onclick", "subQuickAction();");
}
}, 1000);
}


Any ideas?

Answer

You need to iterate over the returned collection from getElementsByClassName. Also, adding a click handler is preferrably done by assigning to the onclick property rather than the attribute.

function loadQuickAction() {
    setTimeout(function() {
        var options = document.getElementsByClassName("select-options");
        for (var i = 0; i < options.length; i++) {
            var children = options[i].childNodes;
            for (var j = 0; j < children.length; j++) {
                children[j].onclick = subQuickAction;
            }
        }
    }, 1000);
}
Comments