Loving the DOM; insert child nodes at any position

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 and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Digg
  • DZone
  • Ma.gnolia
  • MisterWong
  • Reddit
  • scuttle
  • Slashdot
  • SphereIt
  • StumbleUpon
  • YahooMyWeb
  • Wists
discussion by DISQUS
Add New Comment