Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • .prepend() vs .prependTo()
  • .before() vs .insertBefore()
  • .after() vs .insertAfter().
like image 498
webvitaly Avatar asked Jul 18 '12 08:07

webvitaly


2 Answers

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
like image 182
Richard Neil Ilagan Avatar answered Sep 19 '22 19:09

Richard Neil Ilagan


When you are creating an element, it's smoother to use .appendTo equivalents

$("<div>", {text: "hello"}).appendTo("body");

vs

$("body").append( $("<div>", {text: "hello" }) /*Awkward having to call jQuery constructor here*/);
like image 32
Esailija Avatar answered Sep 18 '22 19:09

Esailija