我不想在每个DIV标签后添加元素,而'i = 0','i = 1','i = 2'......直到'max-DIV.length'。我该怎么办?我只是有点担心..哦!
var NewSpan = document.createElement("span");
NewSpan.setAttribute("id", "gotop");
var NewSpanText = document.createTextNode("to be continue...");
NewSpan.appendChild(NewSpanText);
var i = 0;
var OldDiv = document.getElementsByTagName('div')[i];
var parent = OldDiv.parentNode;
if (parent.lastChild == OldDiv) {
parent.appendChild(NewSpan);
} else {
parent.insertBefore(NewSpan, OldDiv.nextSibling);
};
<div id="n1">DIV</div>
<div id="n2">DIV</div>
<div id="n3">DIV</div>
<div id="n4">DIV</div>
答案 0 :(得分:0)
您需要将其包装在for
循环中,并在每次要插入一个元素时创建一个新的span
元素。
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
var NewSpan = document.createElement("span");
NewSpan.setAttribute("id", "gotop" + i); // Can't have duplicate IDs
var NewSpanText = document.createTextNode("to be continue...");
NewSpan.appendChild(NewSpanText);
var OldDiv = divs[i];
var parent = OldDiv.parentNode;
if (parent.lastChild == OldDiv) {
parent.appendChild(NewSpan);
} else {
parent.insertBefore(NewSpan, OldDiv.nextSibling);
}
}
<div id="n1">DIV</div>
<div id="n2">DIV</div>
<div id="n3">DIV</div>
<div id="n4">DIV</div>