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?
If you debug what
$(html)does, you will notice it only creates the DOM tree for the “usefull” contents, here thediv#testblock (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 yourdiv#testelement, you will not be able to search for itself usingfind.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: