简体   繁体   中英

Extracting HTML The Right Way

Strange behavior I noticed. I have a hidden (display:'none') HTML on a page. Then I create a tooltip and extract some data from that hidden HTML into this tooltip, as an example, this way:

 $('#tooltip').html( $('#hiddenElement').html() );

If I modify class name within that hidden html (which is now inside of tooltip) that class name always remains original (unchanged) when it is accessed through DOM:

 alert($('#hiddenElement .element').hasClass('some-class');

So it looks like extracting HTML does not work well as if you use a copy of it which does not reflect DOM. Can anyone explain what really happens? I do not have a test case. Hopefully someone is familiar with what I describe. Thanks

$('#tooltip').html( $('#hiddenElement').html() ); this line will replace #tooltip 's content by #hiddenElement 's content but #hiddenElement remains unchanged.

When you modify anything inside #hiddenElement it will be just for this element. There is no reference to the content which was copied in the earlier line so there will be no change in #tooltip 's content when you modify #hiddenElement 's content.

Instead of html method you should use append method if you want to move content from one element to another.

$('#hiddenElement').html() fetchs the HTML markup under hiddenElement div and the hiddenElement div itself is not included in it.

Hence, you can use something like $('#tooltip .element') to change the class

$('#hiddenElement').html() returns the innerHtml of #hiddenElement as one single string.

Inserting that string into $('#tooltip').html( /*here*/ ); will cause jQuery to detect that you've given a string, and therefore it will continue and parse the string to new HtmlElement 's. This means you've effectively created a clone from the contents of #hiddenElement , in a way that costs a lot more time than jQuery.fn.clone() .

If you do not want to create clones, you could instead use jQuery.fn.contents() :

$('#tooltip').html( $('#hiddenElement').contents() );

However, as this does not clone the contents, it will move them to a new location, and therefore the content will no longer be in the #hiddenElement .

As far as I know, there is no way for a single DOM-node to be in two parent nodes at the same time.

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