Technology

How To Convert Text to HTML using JavaScript

How To Convert Text to HTML using JavaScript;- in this article,we will be using Javascript to convert plain text into HTML element.

HTML (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page’s appearance/presentation (CSS) or functionality/behavior (JavaScript)

String to HTML using Javascript

You can simply convert html string into HTML data for user, by providing contents to div.innerHTML in Javascript but it is better to use DOMParser for better output.

convert string into HTML using these simple steps:

  1. Grab plain text
  2. Check if browser support DOMParser, if yes, convert text into HTML else use fallback
  3. Append Converted HTML into Body.

Here is the Complete Javascript code to do this:

var support = (function () {
	if (!window.DOMParser) return false;
	var parser = new DOMParser();
	try {
		parser.parseFromString('x', 'text/html');
	} catch(err) {
		return false;
	}
	return true;
})();

var textToHTML= function (str) {

	// check for DOMParser support
	if (support) {
		var parser = new DOMParser();
		var doc = parser.parseFromString(str, 'text/html');
		return doc.body.innerHTML;
	}

	// Otherwise, create div and append HTML
	var dom = document.createElement('div');
	dom.innerHTML = str;
	return dom;

};

document.getElementById("divMain").innerHTML= textToHTML('<h1>Hello</h1><p>Your HTML Contents are visible now</p>');

Here is the working fiddle

Convert Plain text into HTML Using jQuery

When using jQuery, you can directly using it’s inbuilt function .html(), here is the custom function

 

$.fn.toHtml=function(){
       return $(this).html($(this).text())
    }

Here is the complete sample HTML

<div id="div">
  Here is the Converted  :&lt;span class="text"&gt; Text&lt;/span&gt; &lt;br /&gt;&lt;a href="javascript:void(0)"&gt;Link&lt;/a&gt;
  
    
</div>
<br />
<input type="button" class="go" value="Convert to HTML ">

and jQuery code

$.fn.toHtml=function(){
       return $(this).html($(this).text())
    }
    $('.go').click(function(){
      $('#div').toHtml()
    
    });

  

Working fiddle

You may also like to read:

About the author

Avatar Of Allglobalupdates

allglobalupdates

All global Updates was established in 2017, and since then we have developed into a renowned group of passionate Content Creators. We concentrate on newsworthy topics in the fields of Finance, Tech, education, Business, Careers, entertainment, and sports. We also create captivating human interest stories and informative content.

Leave a Comment