DEV Community

Cover image for Parse HTML Strings with DOMParser in JavaScript
Dom (dcode)
Dom (dcode)

Posted on

Parse HTML Strings with DOMParser in JavaScript

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


Enter fullscreen mode Exit fullscreen mode

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.";


Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
derwebfluesterer profile image
Michél Keilhauer

Thanks. Good starting article for parse. Like it