javascript - 当追加子节点时,它抛出错误 "Property ' appendChild' does not believe on type 'NodeListOf<Element>' 。”

标签 javascript typescript nodes appendchild

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

相关文章:

javascript - 将 AngularJS 应用程序与 Google Analytics 集成

c - 列表不断打印

java - 如何在Java中计算嵌套数据结构中的叶子节点?

javascript - 异步 typescript 到同步 typescript

typescript - 如何验证用户身份并保存其详细信息

node.js - 错误!无法读取 null 的属性 'path'

javascript - 跟踪一个 Google Analytics 帐户下的多个域名

javascript - Reactjs中如何正确显示和隐藏元素

javascript - 在 Node.js 应用程序中使用 View 模型

javascript - Angular 2. 错误 : Loading chunk failed