Parse HTML Strings with DOMParser in JavaScript

Parse HTML Strings with DOMParser in JavaScript

ยท

2 min read

If you've been following my YouTube channel then you'll know I love discovering new things in JavaScript.

This one is no different. Let's get into it ๐Ÿ˜Ž

Video Tutorial

If you prefer to watch a video tutorial on the DOM Parser, feel free to watch it below ๐Ÿ‘‡

DOM Parser

It's in the name. The DOMParser object will take an HTML/XML string and parse them as an HTMLDocument.

This is really cool.

Let's see it in action:

const html = `
  <html>
      <body>
        <h1 id="title">Page Title</h1>
    </body>
  </html>
`;

const parser = new DOMParser();
const parsedDocument = parser.parseFromString(html, "text/html");

console.log(parsedDocument);

If you were to check the console after running this code, you'll see a full-fledged document object, much like the normal document that comes with each page. ๐Ÿ˜Ž

This means you can do other things such as:

// Select the <h1> page title
const pageTitle = parsedDocument.getElementById("title");

// Update the title's text
pageTitle.textContent = "A new page title.";

The way I see it, there are two main use cases for this feature:

  • creating DOM elements from HTML string (although we have other techniques these days such as <template>)
  • taking an XML document full of data, and parsing it ๐Ÿ˜Š

Either way, I hope you found the DOMParser interesting. Happy coding!

Enrol Now ๐Ÿ‘‰ JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below ๐Ÿ‘‡

https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

ย