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.