无法在JS中设置.color属性

时间:2017-11-20 17:08:51

标签: javascript html

<button id="change_button" class="btn btn-primary" onclick="ColorMe()">CLICK ME</button>

<div class="container">
        <div class="row">
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
        </div>

单击按钮应该将类“grid_element”的所有元素变为红色但从未发生过。

function ColorMe() {
    document.getElementsByClassName("grid_element").style.color = ("red");
}

该问题据说是无法设置undefined的属性'color'     在ColorMe(js.js:2),但我知道它之前以同样的方式工作过很多次。

1 个答案:

答案 0 :(得分:3)

问题是您试图在.style找到的元素集合上使用.getElementsByClassName()属性,而不是集合中的每个元素。

另外(FYI),.getElementsByClassName()返回“实时”节点列表,这会导致每次访问节点列表变量时重新扫描整个DOM,这会对性能产生很大影响。用户的用例有限,因此您可能更经常需要“静态”节点列表。为此,请使用.querySelectorAll()

function ColorMe() {
  // Get all the matching elements into a JavaScript Array
  var elements = Array.prototype.slice.call(document.querySelectorAll(".grid_element"));
  
  // Loop over each element....
  elements.forEach(function(el){
    el.style.color = "red";  // Adjust the element's style
  });    
}
<button id="change_button" class="btn btn-primary" onclick="ColorMe()">CLICK ME</button>

<div class="container">
        <div class="row">
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-4">
                <div class="grid_element">
                    <div class="title">
                        COLOR IS:
                    </div>
                </div>
            </div>
        </div>