Parsing HTML from a JSON string using jQuery

I have no idea what I'm doing wrong, but I have a JSON string with this:

jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World</p></body></html>"}); 

I need to parse this in order to be able to modify the contents. For example, id wants to capture the <p> content.

Now, in jQuery, if I do:

 console.log($(json.content).html()); 

It returns a Title .

If I do:

 console.log($('p',json.content)); 

It returns [] or an empty array.

Finally, if I just: console.log ($ (json.content));

It returns [<title>​Title​</title>​,<p>​Hello World​</p>​]

This is normal, but then I can not do .find() or anything else. Since I don’t know what HTML will be, I cannot use $(json.content)[1] .

Any ideas?

== UPDATE ==

After hacking for a couple of hours, I decided to try XML. My XML example:

 <?xml version=\"1.0\" encoding=\"UTF-8\"?><doc><item>One</item><item>Two</item></doc> 

It gave me the same grief, then it hit me, its a JS object, not a string, and jQuery expects a string. I went and did

 $(JSON.stringify(json.content)).find('item') 

And voila! I got an array of two elements. I was very excited, but then when I went and tried it again with HTML (using JSONP returning the HTML snippet above):

 console.log($(JSON.stringify(json.content)).find('p')); 

I am still getting an empty array. It drives me crazy ... Any ideas?

+4
source share
2 answers

Maybe the best way, but this works (extracts p elements):

 $('<div />', {html: json.content}).find('p'); 
+2
source

What is jsonp443489 here? Why not just make $ .parseJSON?

Once you do this, you can access the content inside it and then create a jquery object from that content and search in it.

var json = $ .parseJSON (jsoncontent); $ (json.content) .find (''); // or you can add it to dom and search using $ ('# id')

-1
source

All Articles