You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS使用getElementsByClassName()设置不同类元素颜色不生效

问题场景

需要通过getElementsByClassName()方法为不同类名的DOM元素设置差异化背景色:

  • 类名为ex的元素背景色设置为蓝色
  • 类名为example的元素背景色设置为红色
    编写代码运行后未达到预期效果,原始实现代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
.example {
  border: 1px solid black;
  padding 8px;
}
</style>
</head>
<body>

<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>

<p>Change the background color of all elements with class="example":</p>

<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>

<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>

<p>A <span class="example">span</span> element with class="example".</p>

<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "red";
}
const collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "blue";
}
</script>

</body>
</html>
问题根因

代码存在3处问题,其中2处会直接阻断功能运行:

  • 核心脚本错误:同一作用域下重复使用const声明同名变量collection。const和let都不支持同一作用域内的重复变量声明,代码运行到第二个const collection时会直接抛出语法错误,导致设置ex类元素背景色的逻辑完全不执行。
  • CSS语法错误:.example选择器内的padding 8px缺少属性名和属性值之间的冒号,会导致该条内边距样式失效。
  • 内容笔误:两个类名为ex的元素内部说明文字错误标注为class="example",不影响功能但会造成内容误导。
修复方案
  1. 为两类元素的DOM集合设置不同的变量名,从根源规避重复声明问题,符合JS编码规范
  2. 补全CSS属性的冒号,修复样式语法错误
  3. 修正元素内的错误说明文本,避免误导

修复后的完整可运行代码:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
  border: 1px solid black;
  padding: 8px;
}
</style>
</head>
<body>

<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>

<p>Change the background color of elements with different classes:</p>

<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="ex"
</div>

<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="ex".
</p>

<p>A <span class="example">span</span> element with class="example".</p>

<script>
const exampleCollection = document.getElementsByClassName("example");
for (let i = 0; i < exampleCollection.length; i++) {
  exampleCollection[i].style.backgroundColor = "red";
}
const exCollection = document.getElementsByClassName("ex");
for (let i = 0; i < exCollection.length; i++) {
  exCollection[i].style.backgroundColor = "blue";
}
</script>

</body>
</html>

内容的提问来源于stack exchange,提问作者Megantara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 20:09:10