2

Please consider the code below.

Here are what I need to happen:

1.) The html tag from variable msg_raw will be rendered as plain html.

2.) The html tag from variable message will be applied, which would mean that the output display will have a red colored ABC text and blue colored <b>DEF</b> text, like so:

ABC           <-- red colored text
<b>DEF</b>    <-- blue colored text

var msg_raw = '<b>DEF</b>';
var message = '<div class="red_text">ABC</div>';
message += '<div class="blue_text">' + msg_raw + '</div>';

$('#some_ID').html(message);
.red_text{ color: red; }
.blue_text{ color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some_ID"></div>
kapitan
  • 2,008
  • 3
  • 20
  • 26

2 Answers2

3

After inserting the <b> as HTML, insert the text that needs to be inside it with .text:

var msg_1 = '<span class="red_text">ABC</span>';

$('#some_ID').html('<b/>');
$('#some_ID > b').text(msg_1);
.red_text{ color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some_ID"></div>

For a more dynamic option, you can replace all characters with a special meaning in HTML with their HTML entity in the msg_raw before concatenating it into message:

// https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
var encodedStr = rawStr => rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
   return '&#'+i.charCodeAt(0)+';';
});

var msg_raw = '<b>DEF</b>';
var message = '<div class="red_text">ABC</div>';
message += '<div class="blue_text">' + encodedStr(msg_raw) + '</div>';

$('#some_ID').html(message);
.red_text{ color: red; }
.blue_text{ color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some_ID"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

you can also use < and > instead < and > :

var msg_1 = '&lt span class="red_text"&gtABC &lt/span&gt';
var msg_2 = '<b>' + msg_1 + '</b>';

$('#some_ID').html(msg_2);
.red_text{ color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some_ID"></div>
Amaresh S M
  • 2,936
  • 2
  • 13
  • 25