Categories
JavaScript Answers

How to add a list item with JavaScript?

Spread the love

Sometimes, we want to add a list item with JavaScript.

In this article, we’ll look at how to add a list item with JavaScript.

How to add a list item with JavaScript?

To add a list item with JavaScript, we can call the document.createElement method to create an li element.

Then we call appenddChild on the list with the li element object as the argument.

For instance, we write:

<ol id="demo"></ol>

to add the ol element.

Then we write:

const list = document.getElementById('demo');
const firstName = 'jane'
const entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);

to select the ol element with document.getElementById.

Then we create the li element with document.createElement.

Next, we call document.createTextNode with firstName to create a text node with the text.

Then we call entry.appendChild to add the text node to the li.

Finally, we call list.appendChild with entry to add the li to the ol.

Now we should see:

1. jane

displayed.

Conclusion

To add a list item with JavaScript, we can call the document.createElement method to create an li element.

Then we call appenddChild on the list with the li element object as the argument.

By John Au-Yeung

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

2 replies on “How to add a list item with JavaScript?”

Hi I’m trying to find solution for my code then I find your website. I find it simple yet elegant. Thanks for the solution.

Leave a Reply

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