I want to parse a html string to jQuery object then find an element by ID.
I tried 3 ways bellow, but only the last works. I don't know why the others not works?
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 the sample: http://jsfiddle.net/nbyofkam/2/
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.
parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).
You could use $('. gettext'). text(); in jQuery.
It's documented :
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed 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 elements inserted may not be representative of the original string passed.
As a result, $(html)
is reduced to "<div id="main"></div>"
. You can verify that by logging $(html)[0].outerHTML
.
So you can't use find
without wrapping it, which is what you do.
An alternate way to do this -
var myTestDiv = document.createElement('div');
var mystr = '<div id="main"></div>';
myTestDiv.innerHTML = mystr;
console.log(myTestDiv.querySelector('div#main'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With