Reputation: 2068
I can't understand the difference between prepend() and prependTo(). can somebody help me understanding the difference.
Upvotes: 6
Views: 7161
Reputation: 179046
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
Upvotes: 5
Reputation: 207501
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.
Which basically says
ElementWhereIWantToAppendTo.prepend(This Is The Content That Is Added)
ElementIWantToAdd.prependTo(This Is Where I add The Content)
Upvotes: 0
Reputation: 78650
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
.
Upvotes: 23