I can't understand the difference between prepend() and prependTo(). can somebody help me understanding the difference.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With