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

JavaScript中两组querySelectorAll元素如何配对赋值innerText

问题原因

你的嵌套forEach逻辑存在逻辑错误:每遍历到一个.oldText元素时,都会完整遍历全部.newText元素对同一个.oldText反复赋值,最终所有.oldText的innerText都会被覆盖为最后一个.newText的内容,所以才会出现全是最后一个值的问题。

解决代码

不需要嵌套循环,利用forEach回调的第二个参数(当前遍历项的索引),直接匹配相同下标的两个元素即可:

<body>
  <h3 class="oldText">oldText</h3>
  <h3 class="oldText">oldText</h3>
  <h3 class="oldText">oldText</h3>
  <h3 class="oldText">oldText</h3>
  <h3 class="oldText">oldText</h3>

  <h3 class="newText">newText1</h3>
  <h3 class="newText">newText2</h3>
  <h3 class="newText">newText3</h3>
  <h3 class="newText">newText4</h3>
  <h3 class="newText">newText5</h3>
  
  <script> 
    const oldText = document.querySelectorAll('.oldText')
    const newText = document.querySelectorAll('.newText')
    // 直接遍历其中一个集合,用索引取对应位置的另一个集合元素
    oldText.forEach((oldT, index) => {
      // 加个判断避免两个集合数量不一致时报错
      if (newText[index]) {
        oldT.innerText = newText[index].innerText
      }
    })
  </script>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:09:04