I wrote a recursive function that traverses nested DOM nodes of the following form:
<a href="#" title="test">
<div id="nested-image">
<img src="image.jpg" />
</div>
</a>
The recursive function is the following:
function getNestedNodes(node) {
var ary = [];
for(var i = 0; i < node.length; ++i) {
var myJSONChildren = {};
if(node[i].childElementCount) {
var myNode = node[i].children;
for(var j = 0; j < myNode.length; ++j) {
for(var k =0, attrs = myNode[j].attributes, l = attrs.length; k < l; ++k) {
myJSONChildren['tag'] = myNode[j].nodeName;
myJSONChildren[attrs.item(k).nodeName] = attrs.item(k).nodeValue;
};
}
myJSONChildren['children'] = getNestedNodes(myNode); //Recursive Call
ary.push(myJSONChildren);
};
}
return ary;
}
so if I call that function this way:
var links = document.querySelectorAll('a');
getNestedNodes(node);
it returns a JSON array of the following form:
[{
tag:'a',
href:"#,
title:"test",
children:[{
tag:"div",
id:"nested-image",
children:[{
tag:"img",
src:"image.jpg"
}]
}]
}]
}]
However, I think that my function is way too complex, and I know that there must a better way to get the same results.
Any help will be greatly appreciated!