Reputation: 3740
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
Upvotes: 1
Views: 104
Reputation: 3031
$('#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.
Upvotes: 1
Reputation: 306
$('#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
Upvotes: 1
Reputation: 69915
$('#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.
Upvotes: 1