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.