Skip to content Skip to sidebar Skip to footer

How To Render Html In String With Javascript?

I have the following javascript code: var html = '
<html><body><h2>HTML</h2></body></html>');

But to append existing HTML string, you need to get the id of the node/tag under which you want to insert your HTML string.

There are two ways by which you can possibly achieve this:

  1. Using DOM -
var tag_id = document.getElementById('tagid');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('html string'));
  1. Using innerHTML -
var tag_id = document.getElementById('tagid');
tag_id.innerHTML = 'HTML string';

Solution 2:

Use $.parseHTML before the append html like as

var html =  '<divclass="col-lg-4 col-references"idreference="'+response+'"><spanclass="optionsRefer"><iclass="glyphicon glyphicon-remove delRefer"style="color:red; cursor:pointer;"data-toggle="modal"data-target="#modalDel"></i><iclass="glyphicon glyphicon-pencil editRefer"data-toggle="modal"data-target="#modalRefer"style="cursor:pointer;"></i></span><divid="contentRefer'+response+'">'+refer_summary+'</div><spanid="nameRefer'+response+'">'+refer_name+'</span></div>';
html = $.parseHTML( html);
$("#references").append(html);

Solution 3:

You can use Javascript's document.createRange().createContextualFragment:

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

/*
  #document-fragment
    <div>One</div><div>Two</div>
*/

https://davidwalsh.name/convert-html-stings-dom-nodes

Solution 4:

You need to assign a particular div an id and then process/change UI in the specific div accordingly.

Given here is an excellent explanation.

Solution 5:

If you want to do it in ReactJS, you can use "dangerouslySetInnerHTML" attribute, instead of "innerHTML" attribute.

As it allows the attackers to inject codes (XSS), it is named dangerous!

const myHtmlData = `
    <ul><li>Item1<li><li>Item2<li></ul>`;
...
<divdangerouslySetInnerHTML={{__html:myHtmlData
}}>

Post a Comment for "How To Render Html In String With Javascript?"