insertAfter function for the DOM

/ Published in: JavaScript
Save to your folder(s)

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

Copy this code and paste it in your HTML
  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

You need to login to post a comment.