我试图用纯JS做一个jquery .after
。
我有以下脚本适用于我追加getElementById
的第一个div,但不适用于我使用的第二个getElementsByClassName
如何使用元素的类成功追加?
HTML
<div id="first-div">First Div - found by ID</div>
<br>
<div class="second-div">Second Div - found by ClassName</div>
JS
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var element1 = document.createElement("div");
element1.className = 'row'
element1.innerHTML = 'Text to append to first div by ID';
var div1 = document.getElementById('first-div');
insertAfter(div1, element1);
var element2 = document.createElement("div");
element2.className = 'row'
element2.innerHTML = 'Text to append to second div by class';
var div2 = document.getElementsByClassName('second-div');
insertAfter(div2, element2);
答案 0 :(得分:1)
var element2 = document.createElement("div");
element2.className = 'row'
element2.innerHTML = 'Text to append to second div by class';
var div2 = document.getElementsByClassName("second-div");
for(var i = 0; i < div2.length; i++)
{
insertAfter(div2.item(i), element2);
}
var div2 = document.getElementsByClassName('second-div');
getElementsByClassName返回一个iterable,所以你必须先说出哪一个[0]
答案 1 :(得分:0)
/
返回该类的所有元素,因此正确的方法是遍历每个项
getElementsByClassName