【问题标题】:I made several divs using JS, however only one of them react to DOM Manipulation我使用 JS 制作了几个 div,但是其中只有一个对 DOM 操作有反应
【发布时间】:2022-01-14 07:48:49
【问题描述】:

我想更改我使用 Javascript 创建的所有 div 的颜色。我的代码应该给它们所有相同的类名和 id 名,但只有其中一个会改变颜色或与我的 DOM 操作交互。你能告诉我我做错了什么,或者我该如何解决?

function makeRows(rows, cols){
for (let i = 0; i < (rows * cols); i++){
  let container= document.getElementById("container");
 let cell= document.createElement("div");
  cell.innerText = (i + 1);
  cell.setAttribute('id','box');
  container.appendChild(cell).className = "gridBox"; 
}
};

makeRows(16,16);

//events

const box= document.getElementById('box');
document.getElementById('box').setAttribute("style", "background-color:red;");

【问题讨论】:

    标签: javascript dom setattribute


    【解决方案1】:

    当您创建多个 div 时,您必须使用 querySelectorAll 来选择类为 .box 的所有元素

    document.querySelectorAll('.box').forEach(box => {
       box.setAttribute("style", "background-color:red;");
    });
    

    【讨论】: