Martyn Ball
Martyn Ball

Reputation: 4885

JavaScript: Unable to check for a class name, says object is undefined

I'm trying to check to see if a group of img objects have got a certain class assigned to them. But for some reason the "hasClass" function is saying that the object I send to it is undefined. When I put the object "imgs[i]" is put in an alert however it displays [object HTMLImageElement]...

Here is the JavaScript:

function print_sales(container) {
    //First of all print the page
    //print();

    //Now check to se eif any images where set to cancel, send the rest
    //to be set to printed in the database
    var container = doc(container);
    var imgs = container.getElementsByTagName('img');
    var printed = new Array();

    //Create a list of id's which have been printed
    for(var i=0;i < imgs.length;i++) {
        if (hasClass(imgs[i], 'print_hide') == false) {
            printed[i] = imgs[i].id;
        }
    }
    alert(printed.toString());
}
function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

Here is my HTML:

<div class="print_container" id="print_container">
    <div data-type="KR">
        <img id="KR_161" onclick="(document.getElementById('KR_161').className == 'print_hide') ? 
        document.getElementById('KR_161').setAttribute('class','') : document.getElementById('KR_161').setAttribute('class','print_hide')" src="php/generateimage.php?imgname=C:/xampp/htdocs/ppa/data/images/20140209/0/1010400_650912468290433_1630439424_n.jpg&amp;restraint=width">
        <img id="KR_162" onclick="(document.getElementById('KR_162').className == 'print_hide') ? 
        document.getElementById('KR_162').setAttribute('class','') : document.getElementById('KR_162').setAttribute('class','print_hide')" src="php/generateimage.php?imgname=C:/xampp/htdocs/ppa/data/images/20140209/0/1505591_650915261623487_1415359740_n.jpg&amp;restraint=width">
        <img id="KR_163" onclick="(document.getElementById('KR_163').className == 'print_hide') ? 
        document.getElementById('KR_163').setAttribute('class','') : document.getElementById('KR_163').setAttribute('class','print_hide')" src="php/generateimage.php?imgname=C:/xampp/htdocs/ppa/data/images/20140209/0/1557590_650910568290623_968124664_n.jpg&amp;restraint=width">
    </div>
</div>

Upvotes: 0

Views: 181

Answers (1)

Evan Trimboli
Evan Trimboli

Reputation: 30082

Your loop condition is wrong. imgs.length will always return true if it's a non-zero value, which means you'll loop forever. You mean to use i < imgs.length.

Upvotes: 3

Related Questions