I am testing jQuery\'s .append()
vs .appendTo()
methods using following code:
$(\'div/>\', {
id : id,
text : $(this).text()
I faced similar query and on researching got some more insights. It was confusing to hear target, element etc and I prefer to visualise the outer selector as $container and element added as $widget. In plain english, I want to add widget to container. Both append and appendTo can be used in the following way and you get exact same result.
$container = $("#containerdiv");
$widget = $("
widget
Approach 1 : $container.append($widget)
Approach 2 : $widget.appendTo($container)
The key difference is what gets returned. In the first case, $container is returned, and in second case, $widget is returned. This will be useful if you are chaining the request with another jquery statement. If you want to work with $container, use first construct and to work with widget, use the second way. For example,
if you want to append 2 widgets to the container, you would give
$container.append($widget1).append($widget2)
and if you want to add a widget and then widget's title to say 'Cool Widget', you would give
$widget.appendTo($container).find('#title').text("Cool Widget")