The parseFromString() method of the DOMParser interface parses a string containing either HTML or XML, returning an HTMLDocument or an XMLDocument .
Syntax
parseFromString(string, mimeType)
Parameters
The string to be parsed. It must contain either an HTML, xml, XHTML, or svg document.
A string. This string determines whether the XML parser or the HTML parser is used to parse the string. Valid values are:
text/html
text/xml
application/xml
application/xhtml+xml
image/svg+xml
A value of text/html will invoke the HTML parser, and the method will return an HTMLDocument . Any element gets marked non-executable, and the contents of are parsed as markup.
The other valid values ( text/xml , application/xml , application/xhtml+xml , and image/svg+xml ) are functionally equivalent. They all invoke the XML parser, and the method will return a XMLDocument .
Any other value is invalid and will cause a TypeError to be thrown.
Return value
An HTMLDocument or an XMLDocument , depending on the mimeType argument.
Note that a MIME type of text/html will invoke the HTML parser, and any other valid MIME type will invoke the XML parser. The application/xml and image/svg+xml MIME types in the example below are functionally identical — the latter does not include any SVG-specific parsing rules. Distinguishing between the two serves only to clarify the code’s intent.
const parser =newDOMParser();const xmlString ="Beware of the tiger";const doc1 = parser.parseFromString(xmlString,"application/xml");// XMLDocumentconst svgString ='';const doc2 = parser.parseFromString(svgString,"image/svg+xml");// XMLDocumentconst htmlString ="Beware of the leopard";const doc3 = parser.parseFromString(htmlString,"text/html");// HTMLDocument console.log(doc1.documentElement.textContent);// "Beware of the tiger" console.log(doc2.firstChild.tagName);// "circle" console.log(doc3.body.firstChild.textContent);// "Beware of the leopard"
Error handling
When using the XML parser with a string that doesn’t represent well-formed XML, the XMLDocument returned by parseFromString will contain a node describing the nature of the parsing error.
const parser =newDOMParser();const xmlString ="Beware of the missing closing tag";const doc = parser.parseFromString(xmlString,"application/xml");const errorNode = doc.querySelector("parsererror");if(errorNode)// parsing failed>else// parsing succeeded>
Additionally, the parsing error may be reported to the browser’s JavaScript console.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
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 !
На выходе получаем объект документа (document), который в элементе body содержит полную разметку, переданную нами в строке.
Более того, если мы передадим не просто HTML-фрагмент документа, а полную HTML-разметку с доктайпами, комментариями и эштемээлями, то на выходе документ будет также хорошо собран. Это важно!
Способ № 2 — Через HTML-элемент iframe
Мы создаём средствами JavaScript новый объект HTML-элемента iframe.
let nif = document.createElement('iframe');
Мы подсаживаем этот iframe в текущий открытый документ, чтобы наш iframe начал участвовать в рендеринге (визуализации) страницы.
Для атрибута srcdoc нашего iframe мы устанавливаем значение — нужную нам строку для парсинга в HTML-документ.
Далее мы дожидаемся события load для iframe, которое будет свидетельствовать о завершении построения объектной модели документа. Это значит, что можно будет работать по новому документу всеми стандартными методами DOM.
let nDoc; nif.onload = (event)=>< // Выводим в консоль №1 console.log(nif.contentDocument); // Выводим в консоль №2 console.log(event.target.contentDocument); // . или. // Сохраняем в перменную №1nDoc = nif.contentDocument // Сохраняем в перменную №2nDoc = event.target.contentDocument >
Далее мы получаем новый объект документа. Внимание! Вложенного документа! Не исходного открытого во вкладке браузера, а вложенного в iframe. Только у отрисованного iframe свойство contentDocument будет содержать нужный нам документ. Если iframe не будет отрисован, а просто создан в дереве родительского документа, то свойство contentDocument вернёт null.
Дополнительная информация
Существует такое понятие, как «фрагмент документа«. Очень важно отличать его от URI-фрагмента, который обозначается решёткой # и имеет связь с элементом на странице по идентификатору id .
Так вот «фрагмент документа» подробно описан в стандарте DOM, в разделе «5.5. Interface Range«. Также имеется отдельный раздел в стандарте DOM Parsing and Serialization, который там называется «8. Extensions to the Range interface«.
Объекты, реализующие интерфейс Range , называются живыми диапазонами (live ranges).
Как это выглядит на практике? Создадим новый объект Range.
Вызовем на полученном объекте Range метод createContextualFragment() . Внутрь метода мы передаём нашу строку с HTML-разметкой:
letdf = nRange.createContextualFragment(stroka)
По итогу нам возвращается новый объект «документ-фрагмент». Какие плюсы мы получаем?
Мы можем обходить вложенные элементы объекта «документ-фрагмент». Это очень круто т. к. по сути нам может быть не всегда нужен полный объект документа!
Например, методом querySelectorAll() с параметром ‘*’ , мы можем получить все объекты элементов, отправленных в первоначальной строке
Или мы можем отобрать все объекты по типу:
[. df.querySelectorAll('*')].filter(element=>element.nodeName=='P') или [. df.querySelectorAll('*')].filter(element=>element.tagName=='P')
К сожалению удобный для работы метод getElementsByTagName() не работает на объектах «документ-фрагмент»
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.