Search code examples
javascriptfunctiononloadclassname

Get element by classname not working


Sorry if i am a noob but this line of code will not work for me some reason it looks correct.

$(window).load(function()  {
    document.getElementByClassName("example").style.width = "50%";
    setTimeout(function () {
       document.getElementByClassName("example").style.width = "50%";
    }, 3000); 
});  

Solution

  • The correct function name is getElementsByClassName, notice the plural form.

    document.getElementsByClassName("example")[0].style.width = "50%";
    //Just an example for how to set the property for the first element
    //we have to iterate over that collection and set property one by one
    

    Also it would yield a node list, so we have to iterate over it to set properties for it.

     var elems = document.getElementsByClassName("example");
     for(var i=0;i<elems.length;i++){
       elems[i].style.width = "50%";
     }
    

    Also note that node list is not an array. Its an array like object. People usually treat them as an array an they will try to use array functions over it. That will results in error. If you want to convert it into an array, then there is a handy function available in EC6, we can use that.

     var arr = Array.from(document.getElementsByClassName("example"));
    

    The above code will transform a node list to an array.