Tukhsanov
Tukhsanov

Reputation: 303

Differences prepend and prependTo. jQuery

I really not understan differences and using prepend and prependTo. Here is my code

HTML

<p>Hello</p>
<p>There</p>

jQuery

var someText = ' Again ';
$('p:first').prependTo(' ' + someText);

but it's not executing.

demo

Upvotes: 1

Views: 655

Answers (4)

adeneo
adeneo

Reputation: 318352

The only difference is the order, with prepend the element to prepend to comes first

var element = $('<div />')
$('p:first').prepend(element);

while prependTo has the element to prependTo last

var element = $('<div />')
element.prependTo($('p:first'));

From the documentation

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.

It's mostly useful for chaining as both methods will return the element the method is applied to, not the element prepended.

Upvotes: 3

siraj pathan
siraj pathan

Reputation: 1495

both used to append text or element to another element

 var someText = ' Again ';
    $('p:first').prepend(' ' + someText);

or you can try this

var someText = ' Again ';
(' ' + someText).prependTo($('p:first'));

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

The is main difference of syntax, see below

$('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");

and

$("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');

For more details see this

Working JSFiddle, here you need to wrap text in some html element. I have wrapped it in a span

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21676

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: 0

Related Questions