Html string from javascript

Converting a string into markup with vanilla JS

Yesterday, I wrote about Reef, my lightweight alternative to Vue and React. Over the next few days, I want to take a look at how various parts of it work under-the-hood.

Today, we’re going to look at how to take an HTML string and convert it into actual markup.

Why you’d need this

If you wanted to inject a string into the DOM, you can do that pretty simply with innerHTML .

app.innerHTML = '

Hello, world!

'
;

But Reef doesn’t just push markup into an element. It compares the existing markup in an element with how it should look, and only updates the things that need to change.

For example, if the existing content inside app was this:

Reef would update just the text inside the h1 instead of creating an entirely new element.

In order for that to work, we need to convert HTML strings into actual HTML elements that can be traversed, mapped, and analyzed.

Creating a helper method

First, let’s create a helper function that will accept a string and return HTML.

/** * Convert a template string into HTML DOM nodes * @param str The template string * @return The template HTML */ var stringToHTML = function (str)  // Code goes here. >; 

The simple approach

The simplest way to do this is to create an element, insert the string into with innerHTML , then return the element.

/** * Convert a template string into HTML DOM nodes * @param str The template string * @return The template HTML */ var stringToHTML = function (str)  var dom = document.createElement('div'); dom.innerHTML = str; return dom; >; 

This approach isn’t perfect, though.

Even though this element is detached—that is, not actually in the existing DOM—the browser will still do things like download image files.

This would trigger an image file to download, even though the markup isn’t displayed anywhere yet.

stringToHTML(''); 

A better way

After doing a bunch of research, I discovered a native browser method that avoids this problem: DOMParser() . The DOMParser() object creates a new DOM document from a string.

To use it, you instantiate a new instance. Then you use the parseFromString() method to convert your string into a new document element. The method accepts the string as it’s first argument. Set the second argument to text/html .

Because it’s literally a new document element, we’ll return the body .

/** * Convert a template string into HTML DOM nodes * @param str The template string * @return The template HTML */ var stringToHTML = function (str)  var parser = new DOMParser(); var doc = parser.parseFromString(str, 'text/html'); return doc.body; >; 

Now we can do this, and no download will be triggered.

stringToHTML(''); 

Combining the two approach

The DOMParser() method is awesome, but the parseFromString() method stops at IE10.

I like to combine the two approaches, using DOMParser() when it’s supported, and falling back to creating an element and using innerHTML when it’s not.

To test for support, we’ll assign an IIFE to the variable support .

Inside the IIFE, we’ll first check if DOMParser exists in the window . If not, we’ll return false . Next, we’ll try to use parseFromString() to create a document . If it fails, we’ll return false . Otherwise, we’ll return true .

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

Inside our stringToHTML() method, we’ll conditionally use DOMParser() when it’s supported, and innerHTML when it’s not.

/** * Convert a template string into HTML DOM nodes * @param str The template string * @return The template HTML */ var stringToHTML = function (str)  // If DOMParser is supported, use it if (support)  var parser = new DOMParser(); var doc = parser.parseFromString(str, 'text/html'); return doc.body; > // Otherwise, fallback to old-school method var dom = document.createElement('div'); dom.innerHTML = str; return dom; >; 

Tomorrow, we’ll look at how to create a map of DOM nodes that we can use for DOM diffing.

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

Html string from javascript

April 26, 2021 — 2 min read

To convert an HTML string into real HTML or DOM, you can use the DOMParser Web API using JavaScript. The DOMParser helps us to parse HTML or XML string into real Document or DOM nodes.

TL;DR

// html string const htmlStr = "

Hello World!

"
; // make a new parser const parser = new DOMParser(); // convert html string into DOM const document = parser.parseFromString(htmlStr, "text/html");

For example, let’s say you have a HTML string of h1 tag with the text of Hello World! like this,

// html string const htmlStr = "

Hello World!

"
;

Now, to convert this string into a real HTML tag we can use the DOMParser web API.

So first, we have to make a parser using the new keyword like this,

// html string const htmlStr = "

Hello World!

"
; // make a new parser const parser = new DOMParser();

After that, we can use the parseFromString() method in the parser object and pass:

  • the raw HTML string as the first argument
  • and the mime type or the type of the document contained in the string as the second argument. In our case, the mime-type value is text/html .

There are other mime types we can use such as:

So it will look like this,

// html string const htmlStr = "

Hello World!

"
; // make a new parser const parser = new DOMParser(); // convert html string into DOM const document = parser.parseFromString(htmlStr, "text/html");

Now the HTML string is converted to an HTML DOM node. You can now use the usual methods and properties available on a DOM node such as appendChild() , classList , etc.

See the above code live in JSBin.

Источник

How to Convert a String to HTML using JavaScript

How to Convert a String to HTML using JavaScript

JavaScript has many built-in APIs and methods that give you control over the HTML on the page.

One of the most useful ways to control the HTML is by converting a string to HTML.

From there, you can use the HTML to append to the DOM, or use it to replace the current page.

In this post, we’ll learn how to convert a string to HTML using JavaScript.

How to convert a String to HTML using JavaScript

To learn how to convert a string to HTML, first let’s define the string of HTML:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`;

Now, we can make use of the built-in DOMParser API to convert the string to HTML.

We already have the string of HTML, so we just need to pass in the type of content to parse, which is text/html :

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html');

From here, we can just take the html and get the body:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); const body = html.body; console.log(body);
 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

We can take the above code and turn it into a reusable function:

 

Convert a String to HTML

Learn how to convert a string to HTML using JavaScript.

`; const convertStringToHTML = htmlString => < const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); return html.body; >const body = convertStringToHTML(htmlString); console.log(body);

If we want, we can take this body and append it to the DOM:

In this post, we learned how to convert a string to HTML using JavaScript.

Simply use the built-in DOMParser class and call the parseFromString() method to convert your string into HTML.

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Convert Text to HTML using Javascript

In one of our previous post, I have explained how to convert word document into HTML using Javascript, in this article,we will be using Javascript to convert plain text into HTML element.

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.

So, we can 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('

Hello

Your HTML Contents are visible now

');

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

Here is the complete sample HTML

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

Источник

Читайте также:  Java annotations string array
Оцените статью