There is no big difference between those functions except the syntax:
$('.target').append('text');
$('text').appendTo('.target');
As said in jQuery docs:
The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), 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.
So in which case it is better to use the .append(), and which .appendTo()? In which code-samples fit only one of those two functions and the other is not good enough?
The same question applies to:
In context
Either way, it's fairly literal and i find myself writing each automatically without thinking.
In each context, if the subject is the area you are manipulating,
seems to make more sense whereas if the subject of the function is new content then
makes more sense.
Chaining Functions
makes more sense than adding another line and vice versa.
Resources
.append() (the jquery documentation)
.appendTo() (the jquery documentation)
a good blog post on the topic (see Difference between .append() and .appendTo() )
It's useful for when you chain a few jQuery actions together. like so:
or:
those two are different actions, hence it is useful to have them both.
You said it yourself --- there's not much difference. My choice of what to use, however, normally depends on method chaining, provided you already have your elements referenced.
i.e.
I think there are two main points to consider:
What do you already have references to? If you already have a jQuery object containing the elements you want to append then it makes sense to use
.appendTo()
rather than selecting the elements you want to append to and then using.append()
.Do you want/need to chain functions? One of the things that jQuery does well is allow you to chain functions together, because every function returns a jQuery object. Obviously if you want to call functions on the elements that you're appending, you'll want to use
.appendTo()
so that any functions you chain after that will apply to the elements being appended, not the elements being appended to.It's mostly a matter of taste.
One situation where
appendTo
is more convenient is when you have a reference to an element rather than a jQuery object, for example in the variabledest
:To use the
append
method you have to create a jQuery object for the element to be able to call it:When you are creating an element, it's smoother to use
.appendTo
equivalentsvs