Get element by classname not working

时间:2016-03-04 18:06:37

标签: javascript function onload classname

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); 
});  

3 个答案:

答案 0 :(得分:4)

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.

答案 1 :(得分:1)

You have $(window) which implies you are trying to utilize jQuery. If you are trying to utilize jQuery make sure it is included on your page. Also it would be easier to write in the following way

$(window).load(function() 
{
$(".example").css('width',"50%");

setTimeout(function () {
  $(".example").css('width', "50%");
}, 3000); 

});  

答案 2 :(得分:-2)

getElementsByClassName is plural. You will most often get more than one answer, in oppose to looking for an ID. So changing your code into:

$(window).load(function() 
{
    document.getElementsByClassName("example").style.width = "50%";

    setTimeout(function () {
        document.getElementsByClassName("example").style.width = "50%";
    }, 3000);
});  

will net you the correct result.