【问题标题】:Appending a child to an a existing element [duplicate]将孩子附加到现有元素[重复]
【发布时间】:2017-08-05 10:34:31
【问题描述】:

我正在尝试动态构建一个模态表单,但是当我搜索我的模态,然后创建一个新的孩子时,它不允许我附加它们。模态是由类设置的,它应该是一个ID吗?请不要参考 w3schools;我正在使用它,它没有帮助。

var a=document.getElementsByClassName('modal');
undefined
var b = document.createElement("p");
undefined
b.appendChild(a);

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at <anonymous>:1:3

【问题讨论】:

    标签: javascript html css nodes dom-manipulation


    【解决方案1】:

    a 将是节点的集合(您通常可以使用 [n] 访问它们,因为它们类似于数组)。你会想拿第一个。试试这个来代替你所拥有的:

    var a=document.getElementsByClassName('modal')[0];

    通常,如果您有多个“类”,则使用“类”。如果您希望它是唯一的,您可以使用“id”。然后你可以使用 `getElementById('xyz') 你会得到一个节点。在这种情况下,不需要在最后做额外的 [0]。

    【讨论】:

    • 真正的 JDG。将调整答案以确保不会误导。谢谢提醒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2014-06-27
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多