How to set DOM element as first child?

Viewed 298474

I have an element E and I'm appending some elements to it. All of a sudden, I find out that the next element to append should be the first child of E. What's the trick, how to do it? Method unshift doesn't work because E is an object, not array.

Long way would be to iterate through E's children and to move'em key++, but I'm sure that there is a prettier way.

9 Answers
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

Unless I have misunderstood:

$("e").prepend("<yourelem>Text</yourelem>");

Or

$("<yourelem>Text</yourelem>").prependTo("e");

Although it sounds like from your description that there is some condition attached, so

if (SomeCondition){
    $("e").prepend("<yourelem>Text</yourelem>");
}
else{
    $("e").append("<yourelem>Text</yourelem>");
}

I think you're looking for the .prepend function in jQuery. Example code:

$("#E").prepend("<p>Code goes here, yo!</p>");
Related