使用JavaScript在所有DIV标记之后添加元素

时间:2016-07-08 20:57:02

标签: javascript while-loop

我不想在每个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>

lile this

1 个答案:

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