user4217999
user4217999

Reputation:

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.

Upvotes: 3

Views: 4452

Answers (3)

user3671377
user3671377

Reputation: 11

Your string formatting is wrong because when i replaced your code with the following code it worked perfectly fine

 <!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

</head>
<body>
    <div id='tester'></div>
    <script >
        var obj = {
        content : "<ul><li>coffee</li><li>tea</li></ul>'"
        };

        $('#tester').append(obj.content); 
    </script> 
</body>
</html>

what i mean to say is you think you are adding a html code but because of your bad string formatting javascript thinks it is a simple string and that is why u see a string added.

Upvotes: 1

Jeremy Rajan
Jeremy Rajan

Reputation: 662

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!

Upvotes: 4

Dave Amit
Dave Amit

Reputation: 2309

You can do something like this ...

var obj = {
    content : '<p>&lt;style&gt;.wrap{color:red}&lt;/style&gt;&lt;div class="wrap"&gt;aa&lt;/div&gt;</p>'
} 

$('span').append($(document.createElement('div')).html(obj.content).text());

fiddler: https://jsfiddle.net/suscmguy/

Your obj.content seems to have invalid / incomplete encoding

Hope this helps...

Upvotes: 2

Related Questions