Posted By

1man on 02/03/07


DOM function inserAfter useful

Versions (?)

Who likes this?

6 people have marked this snippet as a favorite


insertAfter function for the DOM

 / Published in: JavaScript

Vert useful function since there isn't an insertAfter function in the DOM. Call it inside scripts, it expects insertAfter(the new element to be inserted, the element you want it to be inserted after);

  1. //create function, it expects 2 values.
  2. function insertAfter(newElement,targetElement) {
  3. //target is what you want it to go after. Look for this elements parent.
  4. var parent = targetElement.parentNode;
  6. //if the parents lastchild is the targetElement...
  7. if(parent.lastchild == targetElement) {
  8. //add the newElement after the target element.
  9. parent.appendChild(newElement);
  10. } else {
  11. // else the target has siblings, insert the new element between the target and it's next sibling.
  12. parent.insertBefore(newElement, targetElement.nextSibling);
  13. }
  14. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: rojotek on October 13, 2009

Hey 1man -- I've got a client who is interested in this snippet, but is a little cautious regarding copyright. Any chance of putting this explicitly under an apache 2 license?

You need to login to post a comment.