简体   繁体   English

如何使用JavaScript更改类的背景颜色?

[英]how to use JavaScript to change the background color of a class?

I am trying to use javaScript to change the background colour of my class which is called row, My javascript and html code is listed below but its not working and im not sure what the problem is, any help would be greatly appreciated. 我正在尝试使用javaScript更改类的背景颜色,该类称为行。下面列出了我的javascript和html代码,但它不起作用,并且我不确定是什么问题,将不胜感激。

function changeColour() {
    var row = document.getElementsByClassName("row");
    row.style.backgroundColor="black";
}

My html code for the button is listed below. 我的按钮的html代码在下面列出。

<input type="button" id="btnColour" value="Change Colour" 
onclick="changeColour();" />

getElementsByClassName returns a nodeList , an array-like object filled with the matching elements, you have to iterate over that nodeList and set the style on each matching element getElementsByClassName返回一个nodeList ,它是一个充满匹配元素的类似数组的对象,您必须遍历该nodeList并在每个匹配元素上设置样式

function changeColour() {

    var row = document.getElementsByClassName("row");

    for ( var i=0; i<row.length; i++ ) {
        row[i].style.backgroundColor = "black";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM