Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse HTML tags from JSON Object

I have a json object which has a value of html with styles. I tried including it in my html using jquery append.

the value is getting appending, but it is not converting into normal DOM, it is appending the whole thing as a string.

This is my JSON object value:

 var obj = {
    content : "<p>&lt;linkrel=&quot;stylesheet&quot;type=&quot;text/css&quot;href=&quot;http:<p>&lt;styletype=&quot;text/css&quot;&gt;<br/>.wrap{<br/>&nbsp;&nbsp;background-color:#F6F6F6;<br/>}<br/>&lt;/style&gt;</p><p>&lt;divclass=&quot;wrap&quot;&gt;<br/>    &lt;/div&gt;</p>"
}  

This is what i tried:

HTML:

<div id='container'></div>

JS:

$('#container').append(obj.content);

Demo

Output should be a part of dom, instead it is printing the entire thing as a string.


1 Answers

Can you trying doing:

$('#container').append($(obj.content));

That should work. As you are just trying to append text and not DOM elements

Another change being the response JSON, as it has p tags and htmlescaped elements. So, you might have to change the response a bit too, For instance,

  1. Changing the stylesheet link to a style tag, attached to the div.
  2. send the response back as unescaped, which will help reduce the clutter.

Hope that helps!

like image 133
Jeremy Rajan Avatar answered Apr 17 '26 16:04

Jeremy Rajan