Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

getelementbyid - Javascript Append Child AFTER Element

I would like to append an li element after another li inside a ul element using javascript, This is the code I have so far..

var parentGuest = document.getElementById("one");
var childGuest = document.createElement("li");
childGuest.id = "two";

I am familiar with appendChild,

parentGuest.appendChild(childGuest);

However this appends the new element inside the other, and not after. How can I append the new element after the existing one? Thanks.

<ul>
  <li id="one"><!-- where the new li is being put --></li>
  <!-- where I want the new li -->
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...