如何使用 Javascript select 多个索引 ID?

How to select multiple idexed ids using Javascript?

我有 6 divs id wrapperXX 是数字 1 到 6)
当我想使用 for loop
更改其背景颜色时,日志中显示的错误显示为 Uncaught TypeError: Cannot read property 'style' of null
当我不使用模板文字时它可以工作,但我必须一个一个地编写代码

// show error
for (let i = 0; i < 6; i++) { 
  let eleSelect = document.getElementById(`wrapper${i}`);
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}
// it works 
for (let i = 0; i < 6; i++) { 
  let eleSelect = document.getElementById('wrapper0');
  // i must repeat the code till 5
  eleSelect.style.setProperty('background-color', 'green');
  console.log(eleSelect);
}

css代码(我觉得有必要放在这里):

#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px; height: 100px; background-color: black;
} 

html:

<div id="wrapper0"></div><div id="wrapper1"></div><div id="wrapper2"></div><div id="wrapper3"></div><div id="wrapper4"></div><div id="wrapper5"></div>

您的代码没有 wrapper0 元素,但您的循环计数器设置为 0

解决方案:

for (let i = 1; i <= 6; i++) { 
  let eleSelect = document.getElementById(`wrapper${i}`);
  tempEleSelect.style.setProperty('background-color', 'green');
  console.log(tempEleSelect);
}
方法一

第一种方案,选中所有<div>个元素,将所有id属性以wrapper开头的元素的background-color样式设置为green

/** 
 * In the solution below, all <div> elements are selected and the background-color
 * style of all elements whose id attribute starts with "wrapper" is set to green.
 */
let containers = document.querySelectorAll('div');

containers.forEach(element => {
  if(element.getAttribute("id").substring(0, 7) === "wrapper") {
    element.style.setProperty('background-color', 'green');
    console.log(element);
  }
});
#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
  width: 100px; 
  height: 100px; 
  background-color: black;
} 
<div id="wrapper0"></div>
<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
<div id="wrapper4"></div>
<div id="wrapper5"></div>

方法二

在第二个解决方案中,扫描所有 id 值在 [wrapper0, wrapper5] 范围内的项目。如果定义了该元素,则 background-color 样式设置为 green。如果元素未定义,则避免分配任何样式值,因为它的值将是 null.

/**
 * In the solution below, if the selected element is not null, the background-color 
 * style is set to green.
 */
for (let i = 0; i < 6; i++) { 
  let selectedElement = document.getElementById(`wrapper${i}`);

  if(selectedElement !== null) {
    selectedElement.style.setProperty('background-color', 'green');
    console.log(selectedElement);
  }
}
#wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5 {
  width: 100px; 
  height: 100px; 
  background-color: black;
}
<div id="wrapper0"></div>
<div id="wrapper1"></div>
<div id="wrapper2"></div>
<div id="wrapper3"></div>
<div id="wrapper4"></div>
<div id="wrapper5"></div>