Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible jQuery bug parsing HTML

Tags:

jquery

I just discovered this issue, and I wanted to run it by everyone here to make sure I wasn't missing obvious something before I reported it.

Here is what's causing me a problem:

html = '<html><body><div id="test">This is just a test</div></body></html>';
alert( $(html).find('#test').html() );

The alert window shows null instead of the text inside #test. HOWEVER, if I simply wrap <div id="test"> in another div element, it works properly and returns the expected, "This is just a test".

This code works:

html = '<html><body><div><div id="test">This is just a test</div></div></body></html>';
alert( $(html).find('#test').html() );

Can someone explain to me why this would be happening? Why would the second example work but the first one not?

like image 231
Philip Walton Avatar asked Aug 22 '26 23:08

Philip Walton


1 Answers

If you debug what $(html) does, you will notice it only creates the DOM tree for the “usefull” contents, here the div#test block (it strips the html and body containers). Thing is, find() looks for children of the element you're calling it from. As the root element of $(html) is already your div#test element, you will not be able to search for itself using find.

This also explains why wrapping a “container” element makes your code work.

EDIT A simple workaround would be, as the OP said, to warp the html into a container such as a div:

var content = $('<div/>').append(html);
content.find('#test'); // returns the right div
like image 87
zopieux Avatar answered Aug 26 '26 04:08

zopieux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!