I am trying to parse this html through jQuery to get data1, data2, data3. While I do get data2 and data3 I am unable to get data3 with my approach. I am fairly new to jQuery
Its behaviour is weird as it igonores the html and body tag and start from first div with class = "class0". The html is parsed as DOM elements but not added to DOM. For elements added to DOM the selector does not ignore body tag and apply selectors on document. You need to add the html to DOM as given below.
Live Demo
$('#div1').append($(datahtml)); //Add in DOM before applying jquery methods.
alert($('#div1').find(".class0").text()); // Now it Works too
alert($('#div1').find(".class1").text()); // work
alert($('#div1').find("#mydivid").text()); // work
If we wrap your html within some html element to make it starting point instead of your first div with class="class0" then your selector will work as expected.
Live Demo
var datahtml = "<html><body><div><div class=\"class0\"><h4>data1</h4><p class=\"class1\">data2</p><div id=\"mydivid\"><p>data3</p></div></div></div></body></html>";
alert($(datahtml).find(".class0").text()); // Now it Works too
alert($(datahtml).find(".class1").text()); // work
alert($(datahtml).find("#mydivid").text()); // work
What jQuery docs say about the jQuery parsing function jQuery() i.e. $()
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.