Search code examples
jqueryappendprepend

In which case it is better to use the .append(), and which .appendTo()?


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:


Solution

  • 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.

    var _target, _content;
    
    _target.append(_content).addClass('foo');
    // will add the foo class to _target
    
    _content.appendTo(_target).addClass('foo');
    // will add the foo class to _content