jQuery: Append child element before child element
Asked Answered
L

2

5

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?

Latea answered 29/12, 2013 at 9:50 Comment(3)
.prepend() is your friend.Suborder
developer.mozilla.org/fr/docs/DOM/element.insertBeforeNananne
@procrastinator The documentation can be intimidating and that's what this site is for. Anyway I was Googling it myself, this was the first result, and I got my answer (or at least was pointed in the right direction), so mission accomplished.Kimon
C
17

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()

Compress answered 29/12, 2013 at 10:8 Comment(1)
I love how you explained the functions first. Thank youPrajna
L
4

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)
Ladyfinger answered 29/12, 2013 at 9:51 Comment(6)
I guess you have misplaced the selector and content ? it should be insertBeforeCompress
@Compress I think the A is correct. the only difference is in the method usage. $(second).before(first) and $(first).insertBefore(second)Beecham
@RokoC.Buljan yes but the second statement should be insertBefore i guess?Compress
@Compress ahh yes, I see it now.Beecham
@BlackSheep true, but does a String variable.Beecham
@RokoC.Buljan Yes , that's true.Suborder

© 2022 - 2024 — McMap. All rights reserved.