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:
-
insertAtPosition = function(root, el, pos) {
-
//remove any whitespace nodes
-
for(var i=0,j=root.childNodes.length;i<j ;i++){
-
if(x.childNodes[i]===undefined){break;}
-
if(x.childNodes[i].nodeType===3){
-
x.removeChild(x.childNodes[i]);
-
i--;
-
}
-
}
-
//if the position is out of the current scope of the element
-
if(pos>root.childNodes.length || pos<0) {
-
return false;
-
}
-
// if pos is the same as length then add to the end of the children array
-
if (pos===root.childNodes.length) {
-
root.appendChild(el);
-
}
-
// insert before works for all other cases
-
else {
-
root.insertBefore(el, root.childNodes[pos]);
-
}
-
return true;
-
};





Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment