Looking to create some dynamic HTML based on a multidimensional array? That's exactly what I'm trying to do. While handling a one-dimensional array is easy, the varying depth of this array structure presents a challenge.
I should mention that I prefer accomplishing this task without any external JavaScript libraries.
Here's an example of the array I'm working with:
var template = [
['div', {id: 'wrapper'}, [
['link', {rel:'stylesheet', href:'//mysite.com/css.css', type:'text/css'}],
['header', "Look at me! I'm a header!"],
['nav', {class:'main-nav'}, [
['ul', [
['li', ['a', {'href':'/home'}, "Home"]],
['li', ['a', {'href':'/about'}, "About Us"]],
['li', ['a', {'href':'/erase_internet.php'}, "Don't click me!"]]
]]
]],
['section', "Some sample text!"],
['footer', "Copyright © 1984"]
]]
];
The array format follows:
[string "type" [, json obj "attributes" ][, string "text"][, array "children"]]
I already have a function that creates a single element from an array:
function createEl(type, attr, text) {
var key, el = d.createElement(type);
if (typeof attr === 'object' && !Array.isArray(attr)) {
for (key in attr) {
if (attr.hasOwnProperty(key)) {
el.setAttribute(key, attr[key]);
}
}
}
else if (typeof attr === 'string' && text.length > 0) {
el.appendChild(d.createTextNode(attr));
}
if (typeof text === 'string' && text.length > 0) {
el.appendChild(d.createTextNode(text));
}
return el;
}
My goal now is to loop through all the "children" and their descendants as shown in the sample array. The desired output would be structured like this:
<div id="wrapper">
<link rel="stylesheet" href="//mysite.com/css.css" type="text/css" />
<header>Look at me! I'm a header!</header>
<nav class="main-nav">
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/about">About us</a></li>
<li><a href="/erase_internet.php">Don't click me!</a></li>
</ul>
</nav>
<section>Some sample text!</section>
<footer>Copyright © 1984</footer>
</div>
So here are my questions:
- When the array can have multiple levels, what's the best approach for traversing through the
children
and all sub-children
? - Should I call the
createEl()
function recursively to generate and append those child elements?- Is this even feasible?
- Would restructuring the array like this help?:
[string "type" [, json obj "attributes" [, string "text" [, array "children"]]]]
- Is there a more efficient way to achieve this without relying on jQuery or similar libraries? (subjective, but seeking advice from experienced developers)
Appreciate your insights!