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 with VanillaJS
My Comment \ save_comment.php / ... html codes
As you see we got html codes after comment. So, we want to use this string as a DOM.
You don’t need jQuery. Because there is DOMParser class. Our first example’s html code returned like this:
var html = ` <div id="general"> <div class="test"> test234 </div> </div> `
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 = `<html><head><title>Ali GOREN</title></head><body><span>test234</span></body></html>`; 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
If you want to parse xml. You can use DOMParser class. Let’s suppose we have xml like this:
<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
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:
<note> <to>text123</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
That’s all. If you have a question please leave a comment.