jQuery: append() vs appendTo()

后端 未结 1 1727
迷失自我
迷失自我 2021-02-11 16:38

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

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


        
相关标签:
1条回答
  • 2021-02-11 17:40

    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)
提交回复
热议问题