Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Append child element before child element

I have an HTML code like this:

<div id="content">

    <div class="foobar"></div>
</div>

I want to append child elements inside div#content before the div.foobar element. How can do that?

like image 678
Ziyaddin Sadigov Avatar asked Dec 29 '13 09:12

Ziyaddin Sadigov


2 Answers

Before I answer your question let me make something more clearer and easier to u so that you understand what your trying to

Append means you can insert elements as child elements at the end of the selector

example append() and appendTo()

Prepend means you can insert elements as child elements at the beginning of the selector

example prepend() and prependTo()

Notice that selector will be considered as a parent

Before means you can add elements just before the selector

example before() and insertBefore()

After means you can add elements just after the selector

example after() and insertAfter()

before and after does not treat selector as a parent element

Now to answer your question

You can do it using prepend or before

<div id="content">
    <div class="foobar"></div>
</div>

$("your element").insertBefore("#content div.foobar") // or
$("#content div.foobar").before("element") // or
$("#content").prepend("element") // or
$("element").prependTo("#content")

Notice the selector positions in prepend() and prependTo()

like image 112
niko Avatar answered Oct 14 '22 03:10

niko


You can use before()/insertBefore() like

$('#content .foobar').before(newcontent)
$(newcontent).insertBefore('#content .foobar')

or if you want to insert new content as the first child of #content then use prepend()

$('#content').prepend(newcontent)
like image 4
Arun P Johny Avatar answered Oct 14 '22 03:10

Arun P Johny