How to append a dom element inside another dom ele

2019-08-17 02:43发布

问题:

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

回答1:

Use prepend() (docs)

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