JavaScript报错:Uncaught TypeError: textItem.appendChild is not a function求助
解决Uncaught TypeError: textItem.appendChild is not a function错误
嘿,这个错误我太熟啦!咱们来一步步拆解问题:
错误原因
你代码里的textItem是从输入框拿到的文本字符串(document.getElementById('text-item').value),而appendChild是只有DOM元素才有的方法——字符串可不懂这个是什么,自然就报错啦。
修正后的代码
我帮你调整了逻辑,先把文本内容放到创建好的li元素里,再把li加到列表容器中:
const form = document.getElementById('form'); const itemList = document.getElementById('item'); form.addEventListener('submit', addItem); function addItem(e){ e.preventDefault(); // 先拿到输入框的文本值 const textValue = document.getElementById('text-item').value; // 创建li元素并设置类名 const li = document.createElement('li'); li.className = 'item-group'; // 这里补全你原来的类名就行 // 把文本内容放到li里(用textContent比innerHTML更安全) li.textContent = textValue; // 最后把li添加到列表容器中 itemList.appendChild(li); // 可选操作:提交后清空输入框,提升用户体验 document.getElementById('text-item').value = ''; }
小提醒
以后要注意区分:
document.getElementById('text-item'):这是获取到的输入框DOM元素,可以调用DOM相关方法.value:这是从DOM元素里提取出来的字符串值,只能做字符串相关操作
内容的提问来源于stack exchange,提问作者codfish555
相关产品推荐
相关产品推荐

