Manipulating style with getElementsByClassName

后端 未结 5 1349
名媛妹妹
名媛妹妹 2021-01-27 10:25

I don\'t understand why I cannot manipulate the style of .special in my code. I\'m sure it\'s something simple, but it\'s not working.

I am an h1!<

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-27 11:09

    getElementsByClassName returns a list of all elements with class "special", not just one (because there can be multiple elements with the same class name). If you want to get the first element with class "special", do this instead:

    var x = document.getElementsByClassName("special");
    x[0].style.color = "blue";
    

    To change the style of all elements with class "special", you can use a classic for loop:

    var x = document.getElementsByClassName("special");
    for (var i=0; i

提交回复
热议问题