How to modify style to HTML elements (styled externally with CSS) using JS?

前端 未结 3 1326
误落风尘
误落风尘 2020-11-22 00:39

so when i click on the

tag of the home class, i want it to change color to green but it doesn\'t work and idk why. the click registers fine (as the co

3条回答
  •  不要未来只要你来
    2020-11-22 01:36

    .style is actually a js object with keys corresponding to css properties.

    As Adarsh said

    document.getElementsByClassName("home")[0].style.backgroundColor = "green"
    

    Edit - Don't do this. As Scott Marcus explains, this is pretty bad. Definitely should use querySelector('.home') to get the element.

    Generally, if a property has a hyphen like background-color, you convert it to camel case ie backroundColor

    Check out MDN - HTMLElement.style

提交回复
热议问题