EN
JavaScript - parse HTML in web browser
3 points
In this article, we would like to show you how to parse HTML using JavaScript.
It is required that the provided template
element has one root element.
xxxxxxxxxx
1
const parseHtml = (html) => {
2
const container = document.createElement('template');
3
container.innerHTML = html.trim();
4
const nodes = container.content.childNodes;
5
if (nodes.length !== 1) {
6
throw new Error('Indicated HTML must cointain only one root element.');
7
}
8
return nodes[0];
9
};
10
11
12
// Usage example:
13
14
const html = `
15
<div onclick="console.log('Clicked!')">
16
Click me!
17
</div>
18
`;
19
20
const element = parseHtml(html);
21
22
document.body.appendChild(element)
Note:
The
template
element was introduced in HTML5.
Some elements can only be placed in a specific container (e.g. table
-> tbody
-> tr
-> td
).
xxxxxxxxxx
1
const parseHtml = (html, containerTag) => {
2
const container = document.createElement(containerTag || 'div');
3
container.innerHTML = html.trim();
4
const nodes = container.childNodes;
5
if (nodes.length !== 1) {
6
throw new Error('Indicated HTML must cointain only one root element.');
7
}
8
return nodes[0];
9
};
10
11
12
// Usage example 1:
13
14
const html1 = `
15
<div onclick="console.log('Clicked!')">
16
Click me!
17
</div>
18
`;
19
20
const element1 = parseHtml(html1);
21
22
document.body.appendChild(element1);
23
24
25
// Usage example 2:
26
27
const html2 = `
28
<td onclick="console.log('Clicked!')">
29
Click me!
30
</td>
31
`;
32
33
const element2 = parseHtml(html2, 'tr'); // <td> can be placed only inside <tr>
34
// so we use 'tr' as container tag
35
36
document.body.appendChild(element2);
In this example, to parse HTML elements we use the DOMParser
(which in major browsers appeared around 2008-2015).
xxxxxxxxxx
1
// Parses indicated HTML returning new document instance (similar to window.document in JavaScript).
2
//
3
const parseHtml = (html) => {
4
const parser = new DOMParser();
5
return parser.parseFromString(html, 'text/html');
6
};
7
8
9
// Usage example:
10
11
const html = `
12
<div onclick="console.log('Clicked!')">
13
Click me!
14
</div>
15
`;
16
17
const instance = parseHtml(html);
18
19
const htmlElement = instance.documentElement; // <html><head></head><body><div onclick="console.log('Clicked!')">Click me!</div></body></html>
20
const headElement = instance.head; // [empty]
21
const bodyElement = instance.body; // <div onclick="console.log('Clicked!')">Click me!</div>
22
23
console.log(htmlElement.outerHTML);