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
相关产品推荐
相关产品推荐

