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

JavaScript DOM操作新增li元素未插入列表末尾的原因及解决办法

错误原因

你代码中userList的选择器逻辑错误:
document.querySelector(".name-list li")的作用是匹配符合选择器规则的第一个元素,所以你拿到的不是整个<ul>列表容器,而是列表里的第一个<li>元素。此时你调用appendChild方法,实际是把新生成的li插入到了第一个原有li的内部末尾,自然不会出现在整个列表的最后。

修复方法

仅需要修改userList的选择器,获取到外层的ul列表容器即可,调整后的完整JS代码如下:

// 选择器改为选中ul容器本身
const userList = document.querySelector(".name-list");
const listInput = document.querySelector(".list-input");
const addListBtn = document.querySelector(".addListBtn");

addListBtn.addEventListener("click", function(){
    // 可选补充:判断输入内容非空,避免插入空白项
    const inputValue = listInput.value.trim();
    if (!inputValue) return;

    const newLi = document.createElement("li");
    const liContent = document.createTextNode(inputValue);
    newLi.appendChild(liContent);
    // 现在是往ul的内部末尾插入新节点,符合预期效果
    userList.appendChild(newLi);

    // 可选补充:插入完成后清空输入框,优化体验
    listInput.value = '';
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:15:08