alopez02
alopez02

Reputation: 1524

How can I render html code in a div using Javascript or jQuery

I'm trying to render some HTML on the fly in my website without success. I've tried using jQuery's .html() function as below:

My html

<div id='open_ender_output'></div>

My JQuery

var openEnderContent = "&lt;p&gt;&lt;span style="color: #ff0000;"&gt;DDD&lt;/span&gt;!!!!!&lt;strong&gt;666666666666&lt;/strong&gt;&lt;/p&gt;"
//openEnderContent comes from my backend
$('#open_ender_output').html(openEnderContent)

The result is

<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>

Is there a way to make the browser render that result on the fly so it reflects the specific styles set on the text?

Upvotes: 7

Views: 47909

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Decode the content by creating a temporary element.

var openEnderContent = '&lt;p&gt;&lt;span style="color: #ff0000;"&gt;DDD&lt;/span&gt;!!!!!&lt;strong&gt;666666666666&lt;/strong&gt;&lt;/p&gt;';

$('#open_ender_output').html(
  // create an element where the html content as the string
  $('<div/>', {
    html: openEnderContent
  // get text content from element for decoded text  
  }).text()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>


Or you need to use a string which contains unescaped symbols.

var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';

$('#open_ender_output').append(openEnderContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>

Upvotes: 9

Gezzasa
Gezzasa

Reputation: 1453

You're on the right track. You need to differentiate between single and double quotes when creating a string. You're closing your string by adding double quotes inside double quotes.

Use the var below.

var openEnderContent = "<span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>";
$('#open_ender_output').html(openEnderContent);

Fiddle for example: https://jsfiddle.net/acr2xg6u/

Upvotes: 2

Joshua
Joshua

Reputation: 649

Parsing problem from what I can tell.

"&lt;p&gt;&lt;span style="color: #ff0000;"&gt;DDD&lt;/span&gt;!!!!!&lt;strong&gt;666666666666&lt;/strong&gt;&lt;/p&gt;"

You cannot create strings like that. If you are inside one, you must use the other:

"My name is 'Josh Crowe'"
'My name is "Josh Crowe"'

Here's corrected code:

"&lt;p&gt;&lt;span style='color: #ff0000;'&gt;DDD&lt;/span&gt;!!!!!&lt;strong&gt;666666666666&lt;/strong&gt;&lt;/p&gt;"

Upvotes: 0

elementzero23
elementzero23

Reputation: 1429

Change your jQuery to

var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';

$('#open_ender_output').append(openEnderContent);

Upvotes: 1

Related Questions