Lightfire228 Lightfire228 - 1 year ago 108
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=\'\'></param>}"><img src=""><img src=""></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=\'\'></param>}">
<img src="">
<img src="">
<!-- asdf <img> -> -->
Automata Rules!

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

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 Source

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.


    <title>DOM Parser</title>
       var parser = new DOMParser();
       var simpleHTML = "<div class'tst'> <p> hello </p> </div>";
      var htmlObj = parser.parseFromString(simpleHTML, "text/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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download