Categories
JavaScript Answers

How to add new li to ul on click with JavaScript?

Spread the love

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

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

How to add new li to ul on click with JavaScript?

To add new li to ul on click with JavaScript, we can call the appendChild method.

For instance, we write

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

in our click handler function.

We call getElementById to select the ul element.

Then we call createElement to create an li element.

Next, we call createTextNode to create a text node.

Then we call ul.appendChild to append the li as the last child of the ul element.

Conclusion

To add new li to ul on click with JavaScript, we can call the appendChild 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 *