The right way to parse html into a jQuery object

I want to parse the html string for a jQuery object, then find the element by id.

I tried 3 options, but only the latter works. I do not know why others do not work?

var html = "<html><body><div id='main'></div></body></html>"; // Not work, return 0 console.log($(html).find('#main').length); // Not work, return 0 console.log($($.parseHTML(html)).find('#main').length); // Works, return 1 console.log($("<html/>").html(html).find('#main').length); 

Here is an example: http://jsfiddle.net/nbyofkam/2/

+8
javascript jquery
source share
2 answers

It is documented :

When transmitting complex HTML, some browsers may not create a DOM that accurately replicates the provided HTML source. As already mentioned, jQuery uses the browser's .innerHTML property to parse past HTML and insert it into the current document. During this process, some browsers filter out certain elements, such as <html> , <title> or <head> elements. As a result, the inserted items may not match the original passed string.

As a result, $(html) boils down to "<div id="main"></div>" . You can verify by writing $(html)[0].outerHTML .

Thus, you cannot use find without wrapping it, which is what you do.

+9
source share

An alternative way to do this is

 var myTestDiv = document.createElement('div'); var mystr = '<div id="main"></div>'; myTestDiv.innerHTML = mystr; console.log(myTestDiv.querySelector('div#main')); 
+6
source share

All Articles