Skip to content

Instantly share code, notes, and snippets.

@olanod
Last active August 17, 2021 05:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olanod/f89d7ca2ef5cb197d88a to your computer and use it in GitHub Desktop.
Save olanod/f89d7ca2ef5cb197d88a to your computer and use it in GitHub Desktop.
Recursive HTML List
var navigation = createList(globalDataSet);
/**
* Create an HTML list from a tree-like data set
* @param {Array} data Recursive array
* @return {HTMLUListElement} Unordered list with the recursive set of children
*/
function createList(data) {
var listElement = createListElement();
for (var i = 0; i < data.length; i++) {
var node = data[i];
// create an LI for each element in the array
var nodeElement = createListNodeElement(node);
listElement.appendChild(nodeElement);
// if the current elment has a data array create a new list inside
// TODO: change the condition if the data set is different
if('data' in node && node.data.length > 0) {
// recursively append child elements
nodeElement.appendChild(createList(node.data));
}
}
return listElement;
}
/**
* Create custom list element(<ul>)
*/
function createListElement() {
var list = document.createElement('ul');
// TODO: customize list
// e.g. list.classList.add('foo')
return list;
}
/**
* Create custom list node element(<li>)
*/
function createListNodeElement(nodeData) {
var node = document.createElement('li');
// customize list node
// TODO: add more properties, classes, fields, event listeners, etc.
node.textContent = nodeData.title;
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment