无法使用appendChild在JavaScript中附加Child

See*_*ker 0 html javascript

我试图附加一些html作为一个字符串在div中,但一些如何appendChild不按预期工作这里是我的JS代码:

var doc = document.getElementById("products");
var notes = doc.getElementsByClassName("product_grid");


var str = '<div>New Node 3<div><div>New Node 4<div>';

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
notes.appendChild(child);
Run Code Online (Sandbox Code Playgroud)

这是我的HTML:

<div id="products" >
    <div class="product_grid">
        <div>
            Existing node 1
            <div>
        <div>
            Existing node 2
            <div>                
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

它有什么不对,它无法将appendChild识别为一个函数并且TypeError: notes.appendChild is not a function在这里不断给出错误是工作小提琴

Ami*_*oki 6

notes是一个NodeList.所以你必须使用索引来选择元素.

试试这个:

notes[0].appendChild(child); // Appends to first product_grid
Run Code Online (Sandbox Code Playgroud)