我试图附加一些 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);
这是我的 HTML:
<div id="products" >
<div class="product_grid">
<div>
Existing node 1
<div>
<div>
Existing node 2
<div>
</div>
</div>
它有什么问题,它无法将appendChild识别为函数并不断给我错误TypeError:notes.appendChild不是函数
这里是working fiddle
最佳答案
notes
是一个NodeList
。因此,您必须使用索引来选择元素。
试试这个:
notes[0].appendChild(child); // Appends to first product_grid
关于javascript - 无法使用appendChild在JavaScript中追加子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066831/