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

十年热恋 提交于 2019-12-12 04:57:08

问题


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>');


来源:https://stackoverflow.com/questions/9991637/how-to-append-a-dom-element-inside-another-dom-element-but-in-first-position-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!