Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing HTML from a JSON String with jQuery

I have no idea what im 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 to be able to modify the content. Like, for example, id want to grab the <p>'s content.

Now, in jQuery if i do:

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

It returns Title.

If i do:

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

It returns [], or, an empty array.

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

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

Which is fine, but then I cant do .find() or anything. Since I wont know what the HTML will be, i cant use $(json.content)[1].

Any ideas?

==UPDATE==

After hacking at this for a couple hours i decided to try XML. My example XML was:

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

It was giving me the same grief, then it hit me, its a JS object, not a string and jQuery is expecting a string. I went and did

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

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

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

I still get an empty array. It's driving me mad... Any more ideas?

like image 798
Oscar Godson Avatar asked Nov 13 '22 23:11

Oscar Godson


1 Answers

There might be a better way, but this works (retrieves the p elements):

$('<div />', {html: json.content}).find('p');
like image 106
Felix Kling Avatar answered Dec 22 '22 00:12

Felix Kling