How to add new li to ul onclick with JavaScript?

Spread the love

Sometimes, we want to add new li to ul onclick with JavaScript.

In this article, we’ll look at how to add new li to ul onclick with JavaScript.

How to add new li to ul onclick with JavaScript?

To add new li to ul onclick with JavaScript, we call the appendChild method.

For instance, we write

const ul = document.getElementById("list");
const li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);

in our click handler to select the UI with getElementById.

Then we call createElement to create the li element.

And then we call createTextNode to create a text node and append that to the li as its last child with appendChild.

Finally, we call appendChild with li to append the li to the ul as its last child.

Conclusion

To add new li to ul onclick with JavaScript, we call the appendChild method.

Leave a Reply

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