javascript prependChild
You might know appendChild method which allows you to add an element to the end of another. Like this:
someParentObject = document.getElementById("someid");
...
someChildObject = document.createElement("div");
someChildObject.innerHTML = 'Content';
// append the someChildObject to the end of someParentObject
someParentObject.appendChild(someChildObject);
But what to do if you want to add the child object to the very beginning of parent object? I noticed many people are searching for prependChild method. Strange, but… there is no such method.:) Yet there is another trick:
someParentObject.insertBefore(someChildObject,someParentObject.firstChild);
I hope it will help anybody.;-)
UPD. Thanks for people, who noticed my mistake. Of course I was thinking about insertBefore, not appendChild.
March 16th, 2009 at 3:50 am
Nice trick. Works a little better like this –
someParentObject.insertBefore(someChildObject,someParentObject.firstChild);
🙂 But thanks for sharing, definitely helped me out.
May 25th, 2012 at 1:08 pm
I think you have used appendChild where you should be using insertBefore:
Shouldn’t it be
someParentObject.insertBefore(someChildObject,someParentObject.firstChild);
?
September 25th, 2012 at 3:25 pm
Thax a lot working fine with insertBefore()