Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript - How to create nested unordered list based on nesting of array?
In this tutorial, we'll learn how to create nested unordered lists in HTML using JavaScript. We'll use recursion to traverse nested arrays and generate the corresponding HTML structure dynamically.
Understanding the Problem
We need to convert a nested array structure into an HTML unordered list where:
- String elements become list items
- Array elements become nested sublists
- The structure preserves the original nesting levels
For example:
- Coffee
- Cappuccino
- Americano
- Tea
Algorithm
Step 1: Create an HTML container element to hold our generated list
Step 2: Define a nested array with string items and sub-arrays
Step 3: Create a recursive function that processes each array element
Step 4: For each element, check if it's an array or string
Step 5: Create appropriate HTML elements (ul, li) and append them
Step 6: Return the completed unordered list structure
Complete Implementation
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Nested Unordered List Example</title>
<style>
ul { margin: 10px 0; padding-left: 20px; }
li { margin: 5px 0; }
</style>
</head>
<body>
<h2>Nested List from Array</h2>
<div id="listContainer"></div>
<script>
// Define nested array structure
const beverages = [
'Coffee',
['Cappuccino', 'Americano', 'Espresso', 'Mocha'],
'Tea',
['Green Tea', 'Black Tea', ['Earl Grey', 'English Breakfast']],
'Juice',
['Orange', 'Apple', 'Grape']
];
// Recursive function to create nested list
function createNestedList(array) {
const ul = document.createElement('ul');
for (let i = 0; i < array.length; i++) {
const li = document.createElement('li');
if (Array.isArray(array[i])) {
// If element is array, recursively create nested list
li.appendChild(createNestedList(array[i]));
} else {
// If element is string, create text node
li.appendChild(document.createTextNode(array[i]));
}
ul.appendChild(li);
}
return ul;
}
// Generate and display the list
const container = document.getElementById('listContainer');
container.appendChild(createNestedList(beverages));
</script>
</body>
</html>
How the Recursion Works
The function processes each array element:
- String elements: Creates a text node and adds it to a list item
- Array elements: Calls itself recursively to create a nested <ul>
- Result: Each nesting level becomes a new unordered list
Alternative Implementation with Error Handling
function createNestedListSafe(array) {
if (!Array.isArray(array)) {
console.error('Input must be an array');
return document.createTextNode('Invalid input');
}
const ul = document.createElement('ul');
array.forEach(item => {
const li = document.createElement('li');
if (Array.isArray(item)) {
li.appendChild(createNestedListSafe(item));
} else if (typeof item === 'string' || typeof item === 'number') {
li.appendChild(document.createTextNode(String(item)));
} else {
li.appendChild(document.createTextNode('[Invalid item]'));
}
ul.appendChild(li);
});
return ul;
}
// Example with mixed data types
const mixedData = [
'Item 1',
['Subitem A', 'Subitem B'],
42,
['Numbers', [1, 2, 3]]
];
document.getElementById('listContainer').appendChild(createNestedListSafe(mixedData));
Performance Considerations
- Time Complexity: O(n) where n is the total number of elements
- Space Complexity: O(d) where d is the maximum depth of nesting
- Memory Usage: Each recursive call creates new DOM elements
Conclusion
Creating nested unordered lists from arrays using JavaScript recursion provides a flexible way to generate dynamic HTML structures. The recursive approach elegantly handles arbitrary nesting levels, making it perfect for hierarchical data representation.
