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 ๐