Categories
JavaScript Answers

How to Add a New li Element into a ul on Click of an Element with JavaScript?

Spread the love

To add a new li element into a ul on click of an element with JavaScript, we can add a click listener to the element we want to click to add the li with.

For instance, if we have:

<button>
  add
</button>
<ul>

</ul>

Then we can write:

const btn = document.querySelector('button')
const ul = document.querySelector('ul')
btn.addEventListener('click', () => {
  const li = document.createElement("li");
  li.appendChild(document.createTextNode("foo"));
  ul.appendChild(li);
})

to add the click listen to the button with JavaScript.

We get the button an ul elements with document.querySelector .

Then we call addEventListener to add a click listen to the btn button.

In the click listener, we create a new li element with document.createElement .

Then we call li.appendChild to add a text node created by the createTextNode method as its content.

And then we call ul.appendChild with li to add the li into the ul .

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 *