将子节点附加到li时,出现类似类型“NodeListOf”上不存在属性“appendChild”的错误
let li: NodeListOf<Element> = document.querySelectorAll("name li");
var newItem = document.createElement("li");
var ListValue = document.createTextNode("abcd");
var ListValue = document.createTextNode("efgh");
var ListValue = document.createTextNode("ijkl");
newItem.appendChild(ListValue);
li.appendChild(ListItem);
最佳答案
document.querySelectorAll
是一个数组而不是一个元素,你应该迭代你的 li
变量,但我猜测您想要将一个项目添加到现有列表中,如果是这种情况,您应该将该项目附加到列表容器 <ul>...</ul>
编辑:使用document.querySelector
仅选择特定元素
另外,定义新的自定义 html 标记是不好的做法,请尝试使用类来代替,因此对于这样的 html:
<ul class="test">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
使用这个:
let li: NodeListOf<Element> = document.querySelector("ul.test");
var newNumberListItem = document.createElement("li");
var numberListValue = document.createTextNode("java");
var numberListValue = document.createTextNode("ajax");
var numberListValue = document.createTextNode("javascript");
newNumberListItem.appendChild(numberListValue);
li.appendChild(newNumberListItem);
提示:如果您使用 ES6,请避免使用 var
并使用const
对于不会在您的范围内更改的值和 let
对于变量
let li: NodeListOf<Element> = document.querySelector("ul.test");
var newNumberListItem = document.createElement("li");
var numberListValue = document.createTextNode("java");
var numberListValue = document.createTextNode("ajax");
var numberListValue = document.createTextNode("javascript");
newNumberListItem.appendChild(numberListValue);
li.appendChild(newNumberListItem);
<ul class="test">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
关于javascript - 当追加子节点时,它抛出错误 "Property ' appendChild' does not believe on type 'NodeListOf<Element>' 。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395561/