【问题标题】:The error is saying : "list.appendChild is not a function" [duplicate]错误是说:“list.appendChild 不是函数” [重复]
【发布时间】:2019-04-15 20:58:49
【问题描述】:
function addList(value) {
      const list = document.getElementsByClassName("list-div ")
      var div = document.createElement("div");
      div.classList.add("list-new");
       div.innerHTML = `<div class="h5-div" >
          <h5 class="list" >${value}</h5>
          </div>
          <div class="actions" >
          <span class="action-span" ><button 
                  class="action-btn">done</button></span>
          <span class="action-span" ><button 
                 class="action-btn">edit</button></span>
          <span class="action-span" ><button 
                   class="action-btn">delete</button></span>
          </div>`;

      list.appendChild(div);
}

【问题讨论】:

  • getElementsByClassName 将返回一个数组。也许 list[0] 会起作用
  • list 是一个 HTML 集合实例,它没有 appendChild 方法。据我所知,您不能通过该接口添加到 DOM;我不确定这怎么可能有意义。您需要确定您希望新的&lt;div&gt; 在 DOM 中的哪个位置,然后使用 DOM 节点 API 来添加它(例如 appendChild)。

标签: javascript html css-selectors append


【解决方案1】:

当您使用函数将元素附加到列表时,最好的选择是提供 id 而不是类。 如果你想使用这个类,你必须使用 [0] 因为“const list”是一个数组。 您不能将子元素附加到数组中,您需要提供确切的元素。

【讨论】:

    【解决方案2】:

    使用list[0],因为getElementsByClassName 返回一个HTMLCollection(类似数组的对象):

    list[0].appendChild(div);
    

    【讨论】:

    • 谢谢,我不知道 getElementsByClassName 返回一个数组。
    【解决方案3】:

    getElementsByClassName 返回一个 HTML 集合。您可能需要使用 list[0],具体取决于您想要做什么。

    list[0].appendChild(div);
    

    此外,如果您希望在您的 dom 中获得一个唯一列表,您可以考虑使用 document.getElementByID('uniqueId')。您需要创建一个列表:

    <ul id="uniqueId">
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多