Loving the DOM; insert child nodes at any position

Posted by sh1mmer on Dec 11, 2006 in JavaScript |

One day I was bitching about the lack of a way to insert something at an arbitrary point into a list of DOM nodes. "I don't want to walk the DOM, or walk with Dinosaurs, for that matter!" said I, or something equally witty. Steve Webster sick of my whining, no doubt, suggested I write one.

So I did (with a little help from Heilmann).

Here it is in all it's glory

JavaScript:
  1. insertAtPosition = function(root, el, pos) {
  2.  //remove any whitespace nodes
  3.  for(var i=0,j=root.childNodes.length;i<j ;i++){
  4.     if(x.childNodes[i]===undefined){break;}
  5.     if(x.childNodes[i].nodeType===3){
  6.         x.removeChild(x.childNodes[i]);
  7.         i--;
  8.     }
  9.  }
  10.  //if the position is out of the current scope of the element
  11.  if(pos>root.childNodes.length || pos<0) {
  12.  return false;
  13.  }
  14.  // if pos is the same as length then add to the end of the children array
  15.  if (pos===root.childNodes.length) {
  16.  root.appendChild(el);
  17.  }
  18.  // insert before works for all other cases
  19.  else {
  20.  root.insertBefore(el, root.childNodes[pos]);
  21.  }
  22.  return true;
  23. };

Share with friends:
  • Twitter
  • HackerNews
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon

blog comments powered by Disqus

Copyright © 2012 Kid666 Blog All rights reserved. Base theme by Laptop Geek.