document.getElementsByClassName().innerHTML always returns "undefined"

92,642

document.getElementsByClassName() returns a nodeList, not an element!

So it should be :

document.getElementsByClassName('hidden')[0].innerHTML

and as you probably have more .hidden elements, and only want the one inside the current .box (which would be this in the event handler)

this.getElementsByClassName('hidden')[0].innerHTML

but why not jQuery

$(".box").click(function(){
        alert( $('.hidden', this).html() );
});
Share:
92,642

Related videos on Youtube

Blaze Tama
Author by

Blaze Tama

Click here to see my linkedIn profile. (not up to date for now) Email : [email protected] (^_^)

Updated on May 31, 2021

Comments

  • Blaze Tama
    Blaze Tama almost 3 years

    I must have made a mistake somewhere so the document.getElementsByClassName().innerHTML is always returning undefined.

    First i generate the <li> via javascript :

    $('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p><p class="hidden"></p></li>');
    

    Note that in the most right i have a <p> element with hidden class. I use this to get the id which i dont want to show to my users.

    And this is the jQuery to generate the data on those <li> :

    $(".box").each(function () {
        var name, address, picture, id = "";
        if (i < result.length) {
            name = result[i].name;
            address = result[i].address;
            picture = result[i].boxpicture;
            id = result[i].mallid;
        }
    
        $(this).find(".name").html(name);
        $(this).find(".address").html(address);
        $(this).find(".picture").attr("src", picture);
        $(this).find(".hidden").html(id);
        i++;
    });
    

    I have tried to check the data, and its working fine.

    Now, lets say i want to alert the hidden id <p> when user clicks one of those <li class="box"> that i generated above:

    $(".box").click(function () {
        alert(document.getElementsByClassName('hidden').innerHTML);
    });
    

    However this alert always returning "undifined".

    • putvande
      putvande over 10 years
      Just out of curiosity. Why are you using plain JavaScript and jQuery?
  • Blaze Tama
    Blaze Tama over 10 years
    Thanks very much for your help :D Yes, i will try to use just jQuery :D so if i just want to use jQuery, i also need to change "$(this).find(".name").html(name);" to "$('.name', this).html();" right?

Related