views:

72

answers:

4

Simple question - hard to answer, by my experience:

I have element E and I'm appending to it some elements to it. All of a sudden, I find out that next element should be 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 trough E's children and to move'em key++, but I'm sure that there is prettier way.

No?

A: 

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

$("#E").prepend("<p>Code goes here, yo!</p>");
Emil Vikström
You guys are fast! I'm sorry, I think I was misunderstood. element e |- child-el_1 |- child-el_2 |- child-el_3And then comes child-el_4 ... which needs to be fit as first child. prepend would put child-el_4 before [b]e[/b], am I wrong and tired or what?
Popara
A: 

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>");
}
James Wiseman
A: 

Can you further explain? I don't quite understand. Is prependTo what you are looking for?

Tommy
You guys are fast! I'm sorry, I think I was misunderstood. element e |- child-el_1 |- child-el_2 |- child-el_3And then comes child-el_4 ... which needs to be fit as first child. prepend would put child-el_4 before [b]e[/b], am I wrong and tired or what?
Popara
+3  A: 
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);
nemisj
You my friend, just got your self a bear!Useful extra finding. http://docs.jquery.com/Manipulation/insertBefore
Popara