简体   繁体   中英

Where could `appendTo()` be usable with an `htmlString`?

The API docs for appendTo list the method being able to select an HTML string for a target.

However, there seems to be no use to this since the set still includes the original elements, and the HTML string seems not to have been added anywhere in the DOM nor do I see a circumstance where it could be available.

var b = button.appendTo('<div>').appendTo('body');

b is a button, and yet it is not wrapped in a div or anything.

You can see this at http://jsfiddle.net/0dgLe5sj/

Where would it be useful to append to a HTML string (which doesn't yet exist on the page)?

appendTo() returns the item being appended.

So your code is:

var btn = button.appendTo('<div>');
btn.appendTo('body');

As you can see, you move it inside a div, then immediately move it inside the body. So you when you look at it at the end, it's inside the body.

Perhaps you meant:

var b = button.appendTo($('<div>').appendTo('body'));

which will append a div to the body and then append the btn to that div.

Updated fiddle: http://jsfiddle.net/0dgLe5sj/8/

or, if you wanted to add to the div first:

var b = button.appendTo("<div>");
b.parent().appendTo("body")

but if you combine it into a single line, you can't get the button back into the variable using .appendTo as you're adding the div to the body so you're going to get the div or the body back.


To address the 'where would this be useful part':

Being able to create detached DOM elements is extremely useful for parsing HTML strings and can also be used to 'batch' up some changes without forcing page redraws between.

Moving one button to a detached div and the back to the body doesn't have a lot of point, but it proves the principles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM