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.

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:

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

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

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.

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

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:

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:

XML Parsing:

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

We need to change mime type like this:

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

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

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

Live Example

 

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