DOM Parsing with VanillaJS


Hi. In this post I’ll talk about DOM Parsing. As you know jQuery allows manipulate html strings. In last post I wrote about Guid.

DOM Parsing

DOM Parsing with VanillaJS

JavaScript has experimental technology. You can read on MDN. I’ll show DOMParser class. This class be able to manipulate strings as DOM elements. For example you sent ajax request. After that you got response that includes html. Let’s say we want to use an event with that code’s element. Comment form should be best example.

My Comment
     ... html codes

As you see we got html codes after comment. So, we want to use this string as a DOM.

DOMParser Class

You don’t need jQuery. Because there is DOMParser class. Our first example’s html code returned like this:

var html = <code>{{EJS0}}</code>

After that we need to initialize DOMParser class. For example:

var parser = new DOMParser();

We’ll use DOMParser’s parseFromString method. For example:

var parsed = parser.parseFromString(html, "text/html")
console.log(parsed.querySelector("#general > .test").textContent)

Yeah 🙂 Normally we’ll need to “document“. But in this example we don’t need to document.

What if I tried without DOMParser Class?

Yes. I asked this question to myself. Let’s try to example.

var t = <code>{{EJS1}}</code>;

var doc = t.querySelector("span");

We’ll get error because of querySelector metod only works with elements. We’ll see this error:

Uncaught TypeError: t.querySelector is not a function
    at <anonymous>:1:13

I almost forgot. The parseFromString method needs to two argument. For example you didn’t use second argument, you’ll see an error like this:

VM212:1 Uncaught TypeError: Failed to execute 'parseFromString' 
on 'DOMParser': 2 arguments required, but only 1 present.
    at <anonymous>:1:8

Second argument must be one of the mime types as string. So if you use wrong mime types you’ll get error. For example I used “html/text” instead of “text/html” and I got error:

VM221:1 Uncaught TypeError: Failed to execute 'parseFromString' on 'DOMParser': 
The provided value 'html/text' 
is not a valid enum value of type SupportedType.
    at <anonymous>:1:8

XML Parsing:

If you want to parse xml. You can use DOMParser class. Let’s suppose we have xml like this:

    <body>Don't forget me this weekend!</body>

We need to change mime type like this:

var parsed = parser.parseFromString(OUR_XML_STRING, "application/xml");

After that we can use like dom element when we try to select nodes.

parsed.querySelector("note > to").textContent

Above code is important because we can modify XML content. For example I tried like this:

parsed.querySelector("note > to").textContent = "text123"

Our XML structure changed thanks to DOMParser. New structure should be like this:

    <body>Don't forget me this weekend!</body>

Live Example


That’s all. If you have a question please leave a comment.