Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between prepend() and prependTo()

I can't understand the difference between prepend() and prependTo(). can somebody help me understanding the difference.

like image 718
shubendrak Avatar asked Oct 17 '13 17:10

shubendrak


2 Answers

It's really just for chaining.

x.prependTo(y)

Will prepend x to y and return the original collection x.

y.prepend(x)

will also prepend x to y but will return the original collection y.

like image 179
James Montagne Avatar answered Oct 04 '22 02:10

James Montagne


As per the jQuery documentation for prepend

The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.


Some examples:

prepend example 1

<div id="a">
    <p>a</p>
</div>
<div id="b">
    <p>b</p>
</div>
<script>
    $('#a').prepend('#b');
</script>

results in*:

<div id="a">
    #b
    <p>a</p>
</div>
<div id="b">
    <p>b</p>
</div>

this is because prepend treats strings as HTML content rather than selectors

prepend example 2

<div id="a">
    <p>a</p>
</div>
<div id="b">
    <p>b</p>
</div>
<script>
    $('#a').prepend($('#b'));
</script>

results in:

<div id="a">
    <div id="b">
        <p>b</p>
    </div>
    <p>a</p>
</div>

prependTo example 3

<div id="a">
    <p>a</p>
</div>
<div id="b">
    <p>b</p>
</div>
<script>
    $('#a').prependTo('#b');
</script>

results in*:

<div id="b">
    <div id="a">
        <p>a</p>
    </div>
    <p>b</p>
</div>

* whitespace will be wrong in these examples for purposes of making the code readable

like image 41
zzzzBov Avatar answered Oct 04 '22 00:10

zzzzBov