繁体   English   中英

附加childnode时,在类型&#39;NodeListOf&#39;上不存在其抛出错误“ Property&#39;appendChild&#39; <Element> &#39;。”

[英]When appending childnode, its throwing error “Property 'appendChild' does not exist on type 'NodeListOf<Element>'.”

将子节点附加到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> 

li是一个NodeListOf<Element> ,它本身不是Element所以它没有appendChild方法。 您最想做的是解决列表中的一个元素:

li[0].appendChild(newNumberListItem);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM