EN
JavaScript - create <ul> and fill it based on passed array
1
answers
6
points
I would like to create an unordered list (<ul>) from an array of list items.
How can I create a function that creates such a list filled with items based on the array passed into it?
For example, I have an array:
var listItems = ['item 1', 'item 2', 'item 3'];
and the result I want is:
∙ item 1
∙ item 2
∙ item 3
1 answer
6
points
Quick solution:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container"></div>
<script>
function createList(array) {
var list = document.createElement('ul'); // creates list element
for (var i = 0; i < array.length; ++i) {
var item = document.createElement('li'); // creates item element
var text = document.createTextNode(array[i]); // creates text node
item.appendChild(text); // appends text node to item element
list.appendChild(item); // appends item element to list element
}
return list;
}
// Usage example:
var container = document.querySelector('#container');
var listItems = ['item 1', 'item 2', 'item 3'];
var listElement = createList(listItems);
container.appendChild(listElement);
</script>
</body>
</html>
References
0 comments
Add comment