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

原生JS实现从多元素获取innerHTML并生成新列表项的问题

问题解决:原生JS批量提取列表项并添加到目标列表

错误原因

你的代码只能添加第一个列表项,核心问题有两个:

  • 使用document.querySelector('.TestItem')只会返回匹配该类名的第一个元素,无法获取所有目标项
  • window.onload = AutomatedListItemAddition();是直接执行了函数,而非将函数绑定为页面加载完成的回调(括号会让函数立即执行,可能在页面元素未完全加载时就运行,导致获取不到正确元素)

解决方案代码

window.onload = AutomatedListItemAddition;

function AutomatedListItemAddition() {
  const theStoneList = document.getElementById("the-list");
  // 获取所有带TestItem类的元素
  const sourceItems = document.querySelectorAll('.TestItem');

  // 遍历每个源元素,逐个创建并添加新列表项
  sourceItems.forEach(item => {
    // 为每个源元素单独创建新的li和a节点
    const newStoneListItem = document.createElement("li");
    const newStoneListItemA = document.createElement("a");

    // 提取当前源元素的文本和href属性
    const stoneName = item.innerHTML;
    const stoneHref = item.getAttribute("href");

    // 设置新节点的内容和属性
    newStoneListItemA.textContent = stoneName;
    newStoneListItemA.href = stoneHref;
    newStoneListItem.classList.add("filterDiv", "show");

    // 组装节点并添加到目标列表
    newStoneListItem.appendChild(newStoneListItemA);
    theStoneList.appendChild(newStoneListItem);
  });
}

代码原理说明

  • document.querySelectorAll('.TestItem'):返回所有匹配.TestItem类的元素组成的NodeList,支持用forEach遍历每一个元素
  • 遍历过程中为每个源元素单独创建新的DOM节点:避免重复使用同一个节点导致的覆盖问题,确保每个源项都对应一个新的列表项
  • 修正window.onload的赋值:去掉函数后的括号,将函数本身赋值给window.onload,确保页面完全加载后再执行DOM操作
  • 使用textContent替代createTextNode:更简洁地设置文本内容,效果一致但代码更简洁

内容的提问来源于stack exchange,提问作者itzagoodvibe-code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:46:19