How to Add a New li Element into a ul on Click of an Element with JavaScript?
Sometimes, we want to add a new li element into a ul on click of an element with JavaScript.
In this article, we’ll look at how to add a new li element into a ul on click of an element with JavaScript.
Add a New li Element into a ul on Click of an Element with JavaScript
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 .
Conclusion
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.
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: Stackademic | CoFeed | Venture | Cubed
- More content at PlainEnglish.io






