Languages
[Edit]
EN

JavaScript - parse HTML in web browser

3 points
Created by:
telsa
502

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);

 

See also

  1. JavaScript - parse XML in web browser

  2. Node.js - parse html to DOM with htmlparser2 library

References

  1. DOMParser - Web APIs | MDN
  2. DOMParser.parseFromString() - Web APIs | MDN

Alternative titles

  1. JavaScript - how to parse HTML string in web browser?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join