Manipulating style with getElementsByClassName

后端 未结 5 1350
名媛妹妹
名媛妹妹 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 10:50

    Use the for of statement to iterate the collection you get back.

    for (const s of document.getElementsByClassName("special")) {
      s.style.color = "blue";
    }
    

    And I would personally use querySelectorAll instead, since it's more general purpose, and can fetch by class just as easily.

    for (const s of document.querySelectorAll(".special")) {
      s.style.color = "blue";
    }
    

    Lastly, if all .special classes should get that style, it would seem like you could just add it to your CSS instead.

    .special {
      color: blue;
    }
    

    This will depend on other logic that you may have not included in the question though. Even then, you may be able to get away with adding another class, maybe even to some ancestor element.

提交回复
热议问题