While working with web pages, we often need to convert a string to HTML markup. In this article, you’re going to learn how to convert a piece of text or string to an actual HTML element with JavaScript with examples.
Now, how can we convert this? We’re going to use the DOMParser web API to solve the problem.
What is DOMParser :
The DOMParser interface has the ability to transform XML or HTML source code from a string into a DOM Document. It is a tree-based architecture. Let’s use that.
let ConvertStringToHTML = function (str) < let parser = new DOMParser(); let doc = parser.parseFromString(str, 'text/html'); return doc.body; >;
In this code, we have created a function expression and defined a function inside of it. The function simply takes a parameter, so that we can pass our declared string which is ‘ourString’. Then we have created an instance of the DOMParser interface and from the object, we called the built-in method parseFromString() .
The parseFromString() method of the DOMParser interface converts a string which contains HTML and returns as an HTMLDocument.
The parseFromString() the method takes two parameters. The first one is the string we pass and the second one is the type. In our case, we want to convert to an HTML document, so our type is ‘text/html’. Now, if pass our declared string and log this to our console-
console.log(ConvertStringToHTML(ourString));
You can see that the HTML string is converted to an HTML element as a DOM node. Now, you can use the methods of DOM nodes like appendChild() to use the result. The DOMParser also can convert a string to an XML document. We just have to use a different type like ‘text/xml’. So, in this article, you learned how to convert a string to HTML with Javascript. I hope this example will help you. Thank you.
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:
Grab plain text
Check if browser support DOMParser, if yes, convert text into HTML else use fallback
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
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 !
Use innerHTML Property to Convert String to HTML Object
Use DOMParser() Interface to Convert String to HTML Object
Use jQuery to Ensure the Type of the String Passed in HTML
In JavaScript, some specific convention makes the overall developing history one step ahead to be integrated. Likewise, one of the non-static ways of addressing a string (in the form of an HTML element donating pattern) and later passing it to the HTML body as a unique piece of object.
This makes the interface dynamic and can solve many issues that would have been tough to call otherwise.
The code examples in the following content will demonstrate how to implement this conversion. Firstly, we will pass the string with the innerHTML property.
In the next example, we will use the DOM parse method. This convention is not encouraged mostly, as it has issues with acceptance to many browsers.
In the final section, we will examine if the string we passed was an HTML object or just strings. Let’s dive in!
Use innerHTML Property to Convert String to HTML Object
Here, we will have a function stringToHTML that will take the raw string as its parameter. After that, we will create a div , and we wish to pass the string given inside that.
We could also pass it to the HTML body instead, but to be neat, we expect a div element.
Next, the newly created div will be associated with an instance dom (supposedly). So, for dom , we will set the innerHTML property and then pass the string.
The return will be the dom instance for the function stringToHTML we created. Let’s check the code lines.
var stringToHTML =function (str) var dom =document.createElement('div');dom.innerHTML = str;return dom;>;console.log(stringToHTML('
Hello world!
How are you today?
'));
Use DOMParser() Interface to Convert String to HTML Object
The DOMParser() is often ignored or can be used along with conditions. If the prior way of handling the issues gets obliterated, then this segment of code might fire to back up the process.
So here, we will take an instance of the DOMParser() interface, and the instance will be triggered by parseFromString() . The parameters will be the string and the type in HTML it is supposed to represent.
We will then pass the instance doc to the HTML body.
var stringToHTML =function (str) var parser =new DOMParser();var doc = parser.parseFromString(str, 'text/html');return doc.body;>;console.log(stringToHTML('
Hello world!
I am fine Thank you! ^_^
'));
Use jQuery to Ensure the Type of the String Passed in HTML
In this section, we will determine the overall task. We will check if the HTML object was made, the type, etc.
If we can use jQuery to pass a string, it goes to HTML in an object form. Though the content hasn’t been previewed, it has created its space in the HTML body (not permanent).
So, let’s jump to the code block.
htmllang="en">head>metacharset="UTF-8">metahttp-equiv="X-UA-Compatible"content="IE=edge">metaname="viewport"content="width=device-width, initial-scale=1.0">title>Documenttitle>head> body>scriptsrc="https://code.jquery.com/jquery-3.6.0.min.js"integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="crossorigin="anonymous">script>scriptsrc="3.js">script>script>var stringToHTML =function (str) var d = $(str);return d;>console.log(stringToHTML('
Hello world!
How are you today?
'));script>body> html>
Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.
JavaScript | Как преобразовать строку в HTML-элемент?
Рассмотрен случай преобразования готовой разметки HTML, которая лежит в JavaScript в виде строки.
ТВОЯ_СТРОКА — нужно указать свою строку
ТВОЙ_ЭЛЕМЕНТ — нужно указать HTML-элемент, который получается из строки (тот который задумывался изначально)
[0] — это значение опционально, если нужно получить какой-либо один элемент из коллекции элементов. Работает целочисленный индекс как у массивов.
Видео инструкция
В этом видео приводится пример преобразования подготовленной строки в HTML-элемент при помощи JavaScript и стандарта «DOM Parsing and Serialization«. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.
Строка до нужной строки. Или как мы пришли к этому вопросу.
varnewStrLink = stroka.link("efim360.ru")
Мы получили строку, которая полностью оформлена как HTML-разметка ( ВНИМАНИЕ! Это строковый тип данных JavaScript. Не объект DOM интерфейса Element ):
Теперь нам нужно преобразовать эту строку в HTML-элемент, чтобы иметь возможность взаимодействовать как с объектом. (Доставать значения атрибутов, например из href-атрибута)
Решение задачи
Мы воспользуемся интерфейсом DOMParser, который описан в документе — DOM Parsing and Serialization — https://www.w3.org/TR/DOM-Parsing/
Сначала мы создаём новый объект конструктора DOMParser. Вызываем конструктор при помощи оператора new . Не передаём никаких параметров в конструктор.
Затем у этого объекта мы обращаемся к единственному методу parseFromString:
newDOMParser().parseFromString()
Функция parseFromString() принимает два параметра:
Нужная нам строка
Один из пяти Mime-типов в строком виде ( «text/html» , «text/xml» , «application/xml» , «application/xhtml+xml» , «image/svg+xml» )
Передаём нужные параметры:
newDOMParser().parseFromString(newStrLink, "text/html") или newDOMParser().parseFromString(newStrLink, "text/xml")
Нам не нужен сам документ. Нам нужен элемент ссылки, который появился в этом документе.
Мы положили новый документ в переменную и теперь можем отобрать все элементы-ссылки в этом документе (по сути, мы отловим ИМЕННО НАШУ СТРОКУ, с которой начинали)
varaHColl = newDoc.getElementsByTagName("a")
В переменной aHColl будет находиться коллекция HTML-элементов .
Под индексом 0(ноль) будет лежать та самая единственная ссылка, которую из строки мы превратили в объект. У этого объекта будут работать все ключи, которые присущи HTML-элементу .
Мы без проблем сможем обратиться к ключу href и получить его полный путь:
Мы получили href. Всё работает как надо, а значит мы успешно преобразовали строку в HTML-элемент при помощи JavaScript.
Путь № 2 — Использовать «text/xml»
Вариант с «text/xml» вернёт нам «усечённый» документ (не будет и ):
var newStrObject = new DOMParser().parseFromString(newStrLink, "text/xml")
Из него также можно будет получить HTML-коллекцию элементов . НО! ВНИМАНИЕ!
. У этого объекта не будет ключа href.
Объект коллекции не будет содержать нужного количества ключей для своего уникального HTML-элемента. В результате может пострадать логика обработки таких элементов из строк. Будьте внимательны.