Last active
August 17, 2021 05:53
-
-
Save olanod/f89d7ca2ef5cb197d88a to your computer and use it in GitHub Desktop.
Recursive HTML List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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