EN
JavaScript - parse HTML in web browser
3
points
In this article, we would like to show you how to parse HTML using JavaScript.
Practical examples
Example 1
It is required that the provided template
element has one root element.
// ONLINE-RUNNER:browser;
const parseHtml = (html) => {
const container = document.createElement('template');
container.innerHTML = html.trim();
const nodes = container.content.childNodes;
if (nodes.length !== 1) {
throw new Error('Indicated HTML must cointain only one root element.');
}
return nodes[0];
};
// Usage example:
const html = `
<div onclick="console.log('Clicked!')">
Click me!
</div>
`;
const element = parseHtml(html);
document.body.appendChild(element)
Note:
The
template
element was introduced in HTML5.
Example 2
Some elements can only be placed in a specific container (e.g. table
-> tbody
-> tr
-> td
).
// ONLINE-RUNNER:browser;
const parseHtml = (html, containerTag) => {
const container = document.createElement(containerTag || 'div');
container.innerHTML = html.trim();
const nodes = container.childNodes;
if (nodes.length !== 1) {
throw new Error('Indicated HTML must cointain only one root element.');
}
return nodes[0];
};
// Usage example 1:
const html1 = `
<div onclick="console.log('Clicked!')">
Click me!
</div>
`;
const element1 = parseHtml(html1);
document.body.appendChild(element1);
// Usage example 2:
const html2 = `
<td onclick="console.log('Clicked!')">
Click me!
</td>
`;
const element2 = parseHtml(html2, 'tr'); // <td> can be placed only inside <tr>
// so we use 'tr' as container tag
document.body.appendChild(element2);
Example 3
In this example, to parse HTML elements we use the DOMParser
(which in major browsers appeared around 2008-2015).
// ONLINE-RUNNER:browser;
// Parses indicated HTML returning new document instance (similar to window.document in JavaScript).
//
const parseHtml = (html) => {
const parser = new DOMParser();
return parser.parseFromString(html, 'text/html');
};
// Usage example:
const html = `
<div onclick="console.log('Clicked!')">
Click me!
</div>
`;
const instance = parseHtml(html);
const htmlElement = instance.documentElement; // <html><head></head><body><div onclick="console.log('Clicked!')">Click me!</div></body></html>
const headElement = instance.head; // [empty]
const bodyElement = instance.body; // <div onclick="console.log('Clicked!')">Click me!</div>
console.log(htmlElement.outerHTML);