Categories
JavaScript Answers

How to create ul and li elements in JavaScript?

Spread the love

Sometimes, we want to create ul and li elements in JavaScript.

In this article, we’ll look at how to create ul and li elements in JavaScript.

How to create ul and li elements in JavaScript?

To create ul and li elements in JavaScript, we can use the document.createElement method.

For instance, we write:

const createList = (spaceCrafts) => {
  const listView = document.createElement('ol');
  for (const s of spaceCrafts) {
    const listViewItem = document.createElement('li');
    listViewItem.appendChild(document.createTextNode(s));
    listView.appendChild(listViewItem);
  }
  return listView;
}

const spaceCrafts = ['foo', 'bar', 'baz']
const ol = createList(spaceCrafts)
document.body.appendChild(ol)

We create the createList function that takes the spaceCrafts array.

In it, we call document.createElement with 'ol' to create an ordered list element.

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

In the loop, we call document.createElement with 'li' to create an li element.

And we call listViewItem.appendChild with a text node that we create from a spaceCraft entry s.

Finally, we call listView.appendChild with listViewItem to attach it to the listView as its child.

Next, we call createList with spaceCrafts to create the list.

And then we call document.body.appendChild(ol) to append the ol element as a child of the body element.

Conclusion

To create ul and li elements in JavaScript, we can use the document.createElement method.

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 *