无法设置未定义的 属性 'width'

Cannot set property 'width' of undefined

function size(){
for(i=0; i<squares; i++){
    document.getElementById('table').innerHTML += "<div class='squareCell' id='objetive"+i+"'></div>";
}
document.getElementsByClassName('squareCell').style.width="300px";
document.getElementsByClassName('squareCell').style.height="300px";}

仍然收到 "Cannot set property 'width' of undefined",不知道为什么。我不只是想解决这个问题,我想了解这里到底发生了什么。

你好。

getElementsByClassName()方法returns文档中具有指定class名称的所有元素的集合,作为数组对象

如果你有一个 class 名字 squareCell 那么你可以像这样定义第 0 个索引来做到这一点

document.getElementsByClassName('squareCell')[0].style.width="300px";
document.getElementsByClassName('squareCell')[0].style.height="300px";

如果你想做多次使用循环

 var x = document.getElementsByClassName('squareCell');
 for(var i=0; i< x.length;i++){
    x[i].style.width = "300px";
    x[i].style.height = "300px";
 }

var elements = document.getElementsByClassName('squareCell');
  Array.from(elements).forEach(function(element) {
      element.style.height = '50px';
      element.style.width = '50px';
  });

function makeSquare(){
  var elements = document.getElementsByClassName('squareCell');
  Array.from(elements).forEach(function(element) {
      element.style.height = '50px';
      element.style.width = '50px';
  });
}
.squareCell{
    background-color: #ff00ff;
    margin: 5px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}
<button onclick="makeSquare()">Make Square</button>
<br/>
<div class="squareCell">Test1</div>
<div class="squareCell">Test2</div>
<div class="squareCell">Test3</div>
<div class="squareCell">Test4</div>
<div class="squareCell">Test5</div>
<div class="squareCell">Test6</div>