Languages

JavaScript - create <ul> and fill it based on passed array

6 points
Asked by:
Aston-Freeman
787

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
Answered by:
Aston-Freeman
787

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

  1. Document.querySelector() - Web APIs | MDN
  2. Node.appendChild() - Web APIs | MDN
  3. Document.createElement() - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join