Reputation:
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><linkrel="stylesheet"type="text/css"href="http:<p><styletype="text/css"><br/>.wrap{<br/> background-color:#F6F6F6;<br/>}<br/></style></p><p><divclass="wrap"><br/> </div></p>"
}
This is what i tried:
HTML:
<div id='container'></div>
JS:
$('#container').append(obj.content);
Output should be a part of dom, instead it is printing the entire thing as a string.
Upvotes: 3
Views: 4452
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
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,
style
tag, attached to the div
.Hope that helps!
Upvotes: 4
Reputation: 2309
You can do something like this ...
var obj = {
content : '<p><style>.wrap{color:red}</style><div class="wrap">aa</div></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