Lightfire228 Lightfire228 - 15 days ago 5
Javascript Question

Using Javascript DOMParser to format single string HTML to multiline tabbed HTML

For homework in Automata, using DOMParser, we need to format a single string of HTML

<div class="the-best-css-class-like-ever"><div class="youtube-embed" data-oembed="{'version': '1.0', 'type': 'video', 'title': 'Amazing Nintendo Facts', 'html': '<object width=\'425\'><param name=\'movie\' value=\'http://www.youtube.com/v/M3r2XDceM6A&fs=1\'></param>}"><img src="https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png"><img src="https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png"></div><!-- asdf <img> -> --><p>Automata Rules!</p></div>


into a "tabbed", multi line HTML string

<div class="the-best-css-class-like-ever">
<div class="youtube-embed" data-oembed="{'version': '1.0', 'type': 'video', 'title': 'Amazing Nintendo Facts', 'html': '<object width=\'425\'><param name=\'movie\' value=\'http://www.youtube.com/v/M3r2XDceM6A&fs=1\'></param>}">
<img src="https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png">
<img src="https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png">
</div>
<!-- asdf <img> -> -->
<p>
Automata Rules!
</p>
</div>


I have never used Javascript, so how can I use DOMParser to achieve this task?
From what I understand, DOMParser takes HTML and formats it into a tree structure with child elements. However, I've tried to step through the tree, but all I get are
null
and
undefined
values

[EDIT]
Somebody in class gave me a hint to use

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(text, "text/html");
var elements = htmlDoc.body.childNodes;


[EDIT 2]
I solved this by stepping down the DOM tree and getting the HTML, for that particular tag, from the nodes by taking the outerHTML values and removing the childrens' values.

element.outerHTML.replace(child.outerHTML, "");


I couldn't find another, easier way to do this. Alan's answer helped greatly, especially the Firefox dev console and debugger.

Answer

I think you could use it for your task. In your place, I would start with an easier example and then I would go with something harder.

e.g

<html>
   <head>
    <title>DOM Parser</title>
    <script>
       var parser = new DOMParser();
       var simpleHTML = "<div class'tst'> <p> hello </p> </div>";
      var htmlObj = parser.parseFromString(simpleHTML, "text/html"); 
    </script>
   </head>
 <body></body>
</html>

If you load that code snippet in the browser (open the console to debug), you'll see that htmlObj.children will give you an Array with each node, therefore, if you implement your solution using Recursion, you'll be able to solve your homework.

Here you can find more info about DOMParser

Comments