3

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.

3 Answers 3

4

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please provide a example with demo
Can you post a fiddle please? This is the one i tried. jsfiddle.net/318e0mx3
You might have to put the code in dom ready, did you try that?
2

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...

1 Comment

Welcome! Happy coding... ;)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.