How to render HTML in strings with JavaScript?

Javascript Faysal Shuvo

Problem: 

I am a new javascript developer. I have a string that may contain HTML tags. My problem is when I try to render them the tags displayed on the page. For example, It shows <i> tags rather than making the string italic. This is my code: 

const newHtml =  '<div class="col-lg-4 col-references" 
idreference="'+updated_response+'">
<div id="contentRefer'+updated_response+'">'+updated_summary+'</div>
<span id="nameRefer'+updated_response+'">'+updated_name+'</span>
</div>';
$("#references").append(newHtml);

So in this article, we are going to learn how to render HTML in strings with JavaScript?


Solution 1: 

To solve this problem, you can use $.parseHTML before appending the HTML: 

const newHtml =  '<div class="col-lg-4 col-references" 
idreference="'+updated_response+'">
<div id="contentRefer'+updated_response+'">'+updated_summary+'</div>
<span id="nameRefer'+updated_response+'">'+updated_name+'</span>
</div>';
newHtml = $.parseHTML( newHtml);
$("#references").append(newHtml);


Solution 2: 

You can render HTML using document.write().

document.write('<html><body><p>This is a paragraph</p></body></html>');

And if you want to append the existing HTML string. First, you have to get the if of the tag then you can insert your HTML string there. There is two option to do this:

1. You can do this using DOM. This is how you manipulate DOM: 

const getElement = document.getElementById('elementID');
const NewElement = document.createElement('p');
NewElement.appendChild(document.createTextNode('This is a demo string'));


2. Or, you can use innerHTML.

const getElement = document.getElementById('elementID');
getElement.innerHTML = 'This is a demo string';

Hope this solves your problem. If you have any questions you can comment below.