Trying to create a navigation from an existing menu, here’s the markup:
<nav>
<ul id="nav">
<li>
<a href="?=home">Home</a>
<ul>
<li><a href="?=sub-1">Sub 1</a></li>
<li><a href="?=sub-2">Sub 2</a></li>
<li><a href="?=sub-3">Sub 3</a></li>
<li><a href="?=sub-4">Sub 4</a></li>
<li><a href="?=sub-5">Sub 5</a></li>
</ul>
</li>
<li>
<a href="?=about">About</a>
</li>
<li>
<a href="?=services">Services</a>
</li>
<li>
<a href="?=portfolio">Portfolio</a>
</li>
<li>
<a href="?=contact">Contact</a>
</li>
</ul>
</nav>
This is the javascript loop I have, which currently finds and appends each top level menu item, but I really am unsure how to target the nested children and append them with a hyphen for nested elements.
var nav = document.getElementById('nav');
var list = nav.children.length;
for (var i = 0; i < list; i++) {
var option = document.createElement('option');
option.innerHTML = nav.children[i].children[0].innerHTML;
option.value = nav.children[i].children[0].href;
select.appendChild(option);
}
So it would basically do this:
<select>
<option value="?=home">Home</option>
<option value="?=sub-1">- Sub 1</option>
<option value="?=sub-2">- Sub 2</option>
Etc. etc…
Any help would be massively appreciated! Thank you.
You can traverse your ul recursively. That will handle multilevel menus as well. Keep track of the recursion level and the higher level items to concatenate with the dashes.
A description of the approach: http://blog.swapnilsarwe.com/javascript-traversing-html-dom-recursively.html
Edit: Here’s an example. You’ll also need to put an HTML select element with id=’select’ somewhere:
Here’s a fiddle: http://jsfiddle.net/GM54F/3/