JQuery - 为变量分配方法

I was creating a new web page based on the code another developer has written. However there is one part of the code that is really confusing me and I could not find any helpful answers/tips.

So what I am trying to accomplish is to dynamically add rows to a table. The original code is below:

$('#botton').on('click',function(){
    var table = $('#table') ;
    var tr = table.find('tr').first().clone().appendTo(table);

    tr.find('select').selectpicker('val', '');
    tr.find('input').val('');
});

The confusing point for me is how the var tr works. The way I understand the code is: it first gets the current table, then clone the first row and append it to the current table. And then find the row and clean up all previous inputs.

However, since we use appendTo(table) before the cleanup, how can these two codes tr.find('select').selectpicker('val', ''); tr.find('input').val('');

still have effects on what is appending into the table?

I did some testing and changed the code like this

$('#botton').on('click',function(){
    var table = $('#table') ;
    var tr = table.find('tr').first().clone();

    tr.appendTo(table); 

    tr.find('select').selectpicker('val', '');
    tr.find('input').val('');
});

This code seems the same to me but

tr.find('select').selectpicker('val', ''); tr.find('input').val('');

won't have effects on what it appends to the table anymore.

This is my first post so I apologize if I make any editing mistakes. Thanks a ton!

The return value of appendTo() is the jQuery object that's being appended, i.e.

el1 = el2.appendTo(table);

is equivalent to:

el2.appendTo(table);
el1 = el2;

So the code you posted sets tr to the result of clone(), i.e. the new row that was added. Then the following tr.find() calls search in that row.

The general rule in jQuery, like most fluent interfaces, is that methods return the object they were called on if they don't have a more specific value to return, to allow for object chaining. So all these obj.method() calls return obj. This is why there's both append() and appendTo(): container.append(child) returns container, child.appendTo(container) returns child.