- Converting a string into markup with vanilla JS
- Why you’d need this
- Creating a helper method
- The simple approach
- A better way
- Combining the two approach
- Html string from javascript
- TL;DR
- How to Convert a String to HTML using JavaScript
- How to convert a String to HTML using JavaScript
- Convert Text to HTML using Javascript
- String to HTML using Javascript
- Convert Plain text into HTML Using jQuery
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
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.