Mankament Gra Mankament Gra - 1 month ago 8
HTML Question

Object representation HTML

I want to get all elements without textNode in my new Object. I write code and is ok:



var el1 = document.childNodes[0]
var x = el1;

function get(node, ob)
{
ob = ob || {};
var parentNode = node;
var node_length = parentNode.childElementCount

var typElem = parentNode.nodeType
var name = parentNode.nodeName;

for (var x = 0; x < node_length; x++)
{
if (node_length > 0)
{
ob[parentNode.childNodes[x].nodeName] = {}
get(parentNode.childNodes[x], ob[parentNode.childNodes[x].nodeName])
}
else
{

}
};
return ob
}

var o = get(el1)
console.log(o)

<html>
<head></head>
<body>
<h1 id="a">Site 3</h1>
<script src="index.js"></script>
</body>
</html>





It shows me:
Object { HEAD: Object, BODY: Object }


It ok but I want this representation:
HTML:{ HEAD: Object, BODY: Object }


How to modify the function to receive such a result?

Answer

Your recursive function get adds the child nodes of node to ob, so it skips the root html element. What you would want to do is add node to ob instead, and make sure to visit all child nodes.

There are other problems with your code, though, which makes it hard to give a working example without writing the whole thing myself.

An untested example of what you would need to do is something like this:

// add the *current* node to the object, not the children
ob[parentNode.nodeName] = {};

for (var x = 0; x < node_length; x++) {
   // then add the children later
   get(parentNode.childNodes[x], ob[parentNode.nodeName]);
}
Comments