Categories
JavaScript Answers

How to create ul and fill it based on a passed array with JavaScript?

Spread the love

To create ul and fill it based on a passed array with JavaScript, we use the createElement and createTextNode methods.

For instance, we write

const options = ["Option 1", "Option 2"];

const makeUl = (array) => {
  const list = document.createElement("ul");

  for (const a of array) {
    const item = document.createElement("li");
    item.appendChild(document.createTextNode(a));
    list.appendChild(item);
  }
  return list;
};

document.getElementById("foo").appendChild(makeUl(options));

to define the makeUl function.

In it, we create the ul element with createElement.

Then we loop through the array with a for-of loop.

In the loop, we create a li element with createElement.

Then we create a text node with the a content as the text with createTextNode.

Then we call item.appendChild to append the text node to the li as its last child.

And we call list.appendChild to append the li to the ul as its last child.

We then return the list.

Finally, we call makeUl with options and call appendChild to append that as the last child of the element with ID foo.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *