通过ClassName在DOM中查找referenceNode

时间:2017-10-15 16:12:37

标签: javascript dom

我试图用纯JS做一个jquery .after

我有以下脚本适用于我追加getElementById的第一个div,但不适用于我使用的第二个getElementsByClassName

JSFiddle

如何使用元素的类成功追加?

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);

2 个答案:

答案 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