I have this JSON layout:
[
{
"tag": "div",
"attr": [
["id", "sortSideStyleIlluminated"],
["class", "sortSideWidget"]
],
"childs": [
{
"tag": "img",
"attr": [
["class", "sortSide"],
["src","/images/sort-side-col/style-illuminated.jpg"],
["width", 185],
["height", 58],
["alt", "Style Illuminated"]
]
},
{
"tag": "br"
},
{
"tag": "br"
},
{
"tag": "div",
"text": "This div have childs",
"childs": [
{
"tag": "b",
"text": "hellow"
}
]
}
]
},
{
"tag": "div",
"attr": [
["id", "sortSideStyleIlluminated"],
["class", "sortSideWidget"]
],
"childs": [
{
"tag": "img",
"attr": [
["class", "sortSide"],
["src","/images/sort-side-col/style-illuminated.jpg"],
["width", 185],
["height", 58],
["alt", "Style Illuminated"]
]
},
{
"tag": "br"
},
{
"tag": "br"
},
{
"tag": "span",
"text": "Widget 2"
}
]
}
]
I’m trying to render the page using a self-calling function to render all the childs of childs of childs… but I don’t know for what reason my function just renders two level of childs. My function:
function renderWidgets(order){
var result = document.createElement('div'),
createEl = function(el){
var element = document.createElement(el.tag);
for(var i in el.attr){
if(el.attr[i]) element.setAttribute(el.attr[i][0], el.attr[i][1]);
}
for(var i in el.childs){
var child = createEl(el.childs[i]);
child.innerHTML = el.childs[i].text ? el.childs[i].text : "";
element.appendChild(child);
}
return element;
};
for(var i in order){
if(widgets[order[i]]){
var widgetElement = createEl(widgets[order[i]]);
result.appendChild(widgetElement);
}
}
return result;
}
document.body.appendChild(renderWidgets([0,1]));
Can you take a look at the code and see what’s wrong here?
Thanks,
Live at JSBin: http://jsbin.com/ilubic/edit#javascript,html,live
Try a truly recursive function instead:
call it as:
If you want to take care of the
order, you really should do it outside of the function to keep things clean and separate.