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

Spread the love

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

For instance, we write

<ul id="list">
  <li id="element1">One</li>
  <li id="element2">Two</li>
  <li id="element3">Three</li>
</ul>

to add a ul element.

Then we write

document.body.onclick = () => {
  const ul = document.getElementById("list");
  const li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
};

to add a click listener to the body element by setting the document.body.onclick property to a function that gets the ul with getElementById.

And then we create an li element with createElement.

Then we append the li element with a text node created with createTextNode.

And we call ul.appendChild to append the li to the ul.

Leave a Reply

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