jQuery: append() vs appendTo()

后端 未结 3 870
礼貌的吻别
礼貌的吻别 2021-02-11 16:58

I am testing jQuery\'s .append() vs .appendTo() methods using following code:

$(\'div/>\', {
    id : id,
    text : $(this).text()
         


        
相关标签:
3条回答
  • 2021-02-11 17:21

    append appends the parameter to the object you're working on.

    appendTo appends the object you're working on to the parameter.

    More info here: http://api.jquery.com/appendTo/

    aside from that, there is something wrong here:

    $('div/>',
    

    this is not selecting anything.

    0 讨论(0)
  • 2021-02-11 17:26

    To answer the question, you don't have an element to appendTo anything, as you're missing characters (in your case it's an opening angle bracket <).

    This

    $('div/>',{});
    

    needs to be

    $('<div/>',{});
    

    to create an element, otherwise it does exactly what you say it does - nothing!


    Otherwise you seem to have the order of things right, it's like this:

    • .append() inserts the content specified by the parameter, to the end of each element in the set of matched elements, as in

      $(Append_To_This).append(The_Content_Given_Here);
      
    • while .appendTo() works the other way around: it insert every element in the set of matched elements to the end of the target given in the parameter, as in

      $(The_Content_Given_Here).appendTo(Append_To_This);
      


    There's also .prepend() and prependTo() which works exactly the same, with the only difference being that the prepended elements are added at the beginning of the target elements content instead of the end.

    0 讨论(0)
  • 2021-02-11 17:45

    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 = $("<div> <h1 id='title'> widget </h1> </div>")

    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")

    0 讨论(0)
提交回复
热议问题