hierarchy([
'First item',
'Second item',
'Third item',
// ...
]); // Should create a pyramid hierarchy in HTML after using this function
Assistant
Here's a JavaScript function that takes an array of strings and creates a nested HTML hierarchy in the form of a pyramid (nested lists):
javascript
function hierarchy(items) {
if (items.length === 0) return;
var parent = document.body;
var ul = document.createElement('ul');
parent.appendChild(ul);
var li = document.createElement('li');
li.textContent = items[0];
ul.appendChild(li);
parent = li;
for(var i = 1; i < items.length; i++) {
ul = document.createElement('ul');
li = document.createElement('li');
li.textContent = items[i];
ul.appendChild(li);
parent.appendChild(ul);
parent = li;
}
}
You can use this function by passing an array of strings to it. For example:
Each <li> contains a nested <ul> which in turn contains the next <li>, creating a pyramid-like hierarchical structure.
Usage Notes:
Make sure to call this function after the DOM is fully loaded. You can place your script at the end of the <body>, or wrap your code inside a window.onload event:
The function appends the hierarchy directly to the document.body. If you want to append it to a specific element, modify the parent variable initialization:
javascript
var parent = document.getElementById('your-element-id');
Live Example:
You can see this function in action by creating a simple HTML file:
html
<!DOCTYPE html>
<html>
<head>
<title>Hierarchy Example</title>
</head>
<body>
<script>
function hierarchy(items) {
if (items.length === 0) return;
var parent = document.body;
var ul = document.createElement('ul');
parent.appendChild(ul);
var li = document.createElement('li');
li.textContent = items[0];
ul.appendChild(li);
parent = li;
for(var i = 1; i < items.length; i++) {
ul = document.createElement('ul');
li = document.createElement('li');
li.textContent = items[i];
ul.appendChild(li);
parent.appendChild(ul);
parent = li;
}
}
hierarchy([
'First item',
'Second item',
'Third item',
'Fourth item',
'Fifth item'
]);
</script>
</body>
</html>
Styling the Hierarchy:
To enhance the visual appearance of your hierarchy, you can add some CSS styles. For instance: