JSFiddle - React, Tailwind, and code Playground
by Константин Дралюк
HTML
<div id="menu"></div>
JavaScript
var menuArray = [
{
'title': 'Home',
'href': 'index.html'
},
{
'title': 'Blog',
'href': 'blog.html',
'sub': [
{
'title': 'All posts',
'href': 'blog-all.html'
},
{
'title': 'Last posts',
'href': 'blog-last.html',
'sub': [
{
'title': 'Hello, world!',
'href': 'hello-world.html'
}
]
}
]
},
{
'title': 'Contacts',
'href': 'contacts.html'
}
]
var menu = document.querySelector('#menu');
var structure = '';
function buildMenu(menuArray) {
if (menuArray && Array.isArray(menuArray)) {
structure += '<ul>';
menuArray.forEach(function(item){
if (item) {
structure += `<li><a href="${item.href || "#!"}">${item.title}</a>`;
if (item.sub) {
buildMenu(item.sub);
}
structure += `</li>`;
}
});
structure += '</ul>';
}
}
buildMenu(menuArray);
window.structure = structure;
menu.innerHTML = structure;