Alon
Alon

Reputation: 7758

How to append a dom element inside another dom element but in first position in jquery

I have this html:

<div id="wrapper">
     <div class="inner">Inner</div>
     <div class="inner">Inner</div>
     <div class="inner">Inner</div>
</div>

I want to append this line

<div id="first">first</div>

between the div#wrapper and the first div.inner - so it will always be the first element even if there are no elements.

so it will look like this:

<div id="wrapper">
     <div id="first">first</div>
     <div class="inner">Inner</div>
     <div class="inner">Inner</div>
     <div class="inner">Inner</div>
</div>

or in case I have no .inner div's it will look like this:

<div id="wrapper">
     <div id="first">first</div>
</div>

How do I do that? thanks, Alon

Upvotes: 0

Views: 339

Answers (1)

Rene Pot
Rene Pot

Reputation: 24815

Use prepend() (docs)

$('#wrapper').prepend('<div id="first">first</div>');

Upvotes: 5

Related Questions