Ajax Response Find HTML snippets with Find

I tested JQuery, I have an html response coming from an AJAX request, so initially the result would be like this.

<!DOCTYPE html> <html> <body> <div id="dashboard"> <div id="dash2"> <h1>Hi</h1> </div> </div> </body> </html> 

In my Ajax success code this is ..

 success : function(response,status) { console.log( $(response).find('#dashboard').html() ); } 

After printing to the console, which gives me undefined .

However, when I change the response page (I created a nesting div) to this

 <!DOCTYPE html> <html> <body> <div id="div1"> <div id="dashboard"> <div id="dash2"> <h1>Hi</h1> </div> </div> </div> </body> </html> 

The line from my Ajax success code returned console.log( $(response).find('#dashboard').html() ); returned

 <div id="dash2"> <h1>Hi</h1> </div> 

My question is. How did the first HTML appear when executing console.log( $(response).find('#dashboard').html() ); , he gave me undefined, however on the second HTML (the one that is embedded in the div) gave me the contents of #dashboard (which is the one I expect to receive.

+4
source share
2 answers

As far as I know, this is a browser-specific behavior to which tags fall as a measure of sanitation, for example. <head/> .

Reason for not finding #dashboard at runtime

 $(response).find('#dashboard') 

most likely because #dashboard became the root element after sanitation, and .find() corresponds to descendant elements that do not belong to the root itself.

Generally, to avoid this problem, do this on an empty <div> .

 $("<div/>").html(response).find('#dashboard') 
+4
source

jQuery breaks everything except the contents of the body, so #dashboard is at the top level, so find will actually look for descendants of #dashboard . Since #dashboard is at the top level, you can use a filter to select it from other top-level nodes.

http://jsfiddle.net/mowglisanu/SqL9Q/

0
source

All Articles