How can I append a childNode to a specific position in javascript?
I want to add a childNode to the 3rd position in a div. There are other nodes behind it that need
Simplified,
Element.prototype.insertChildAtIndex = function(child, index) {
if (!index) index = 0
if (index >= this.children.length) {
this.appendChild(child)
} else {
this.insertBefore(child, this.children[index])
}
}
Then,
var child = document.createElement('div')
var parent = document.body
parent.insertChildAtIndex(child, 2)
Tada!
Be aware of when extending natives could be troublesome