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 so please pardon my ignorance.
<html>
<body>
<div class="class0">
<h4>data1</h4>
<p class="class1">data2</p>
<div id="mydivid"><p>data3</p></div>
</div>
</body>
</html>
Here is how I am calling this in my jquery.
var datahtml = "<html><body><div class=\"class0\"><h4>data1</h4><p class=\"class1\">data2</p><div id=\"mydivid\"><p>data3</p></div></div></body></html>";
alert($(datahtml).find(".class0").text()); // Doesn't Work
alert($(datahtml).find(".class1").text()); // work
alert($(datahtml).find("#mydivid").text()); // work
Only alert($(datahtml).find(".class0").text()); is not working the rest are working as expected. I am wondering it may be because class0 has multiple tag inside it or what?? How to get data1 in such scenario?
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
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
What jQuery docs say about the jQuery parsing function jQuery() i.e. $()