How to Render HTML in strings with JavaScript?

To Render HTML in strings with Javascript, either use document.write(Using DOM or innerHTML), or can achieve using $.parseHTML or using the document.createRange().

The article below will in detail discuss “How to render HTML in strings with JavaScript?” and will help you understand the how to render HTML tags on a much deeper level.

When you try to render the HTML tags displayed on your page in javascript. You can use below mentioned methods:

Method 1: Using document.write

The first method is to use document.write, to render HTML tags. You can follow the below mentioned example to know how to do so:

document.write('<html><body><p> a sentence.</p></body></html>');

Additionally, if you wish to add to the current HTML string. You must first obtain the if of the tag before you can place your HTML string there. There are two ways to go about it:

Step 1: Using DOM

You can use DOM to add the current HTML string. You can follow the below mentioned example to know how to do so:

const getElement = document.getElementById('elementID');
const NewElement = document.createElement('p');
NewElement.appendChild(document.createTextNode('Trail string'));


Step 2: Using innerHTML

You can use innerHTML to add the current HTML string. You can follow the below mentioned example to know how to do so:

const getElement = document.getElementById('elementID');
getElement.innerHTML = 'Trail string';

Method 2: Using $.parseHTML

The second method is to use $.parseHTML, to render HTML tags. You can follow the below mentioned example to know how to do so:

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);

Method 3: Using document.createRange()

The third method is to use document.createRange().createContextualFragment:, to render HTML tags. You can follow the below mentioned example to know how to do so:

const frag = document.createRange().createContextualFragment('<div>1</div><div>2</div>');
console.log(frag);

/*
  #document-fragment
    <div>1</div>
    <div>2</div>
*/

Method 4: For React.js

The fourth method is for react.js is to use "dangerouslySetInnerHTML" attribute, in place of "innerHTML" attribute.

It is referred to as harmful because it permits attackers to inject programmes (XSS)! You can follow the below mentioned example to know how to do so:

const myHtmlData = `
    <ul>
        <li>1<li>
        <li>2<li>
    </ul>`;
...
<div
    dangerouslySetInnerHTML={{
        __html: myHtmlData
}}>