YogeshChauhan.com
How to add and remove list items using JavaScript?
February 13, 2021

In this post, I demonstrated how to create HTML elements using JavaScript. That’s what we are going to use to create elements.

Let’s add couple of list elements with id and a button with id.

Now, let’s add the onclick event to the button element, get the list element and using createElement, create the new li element.

We need to add id to all those elements we create so that we can target them to delete.

Let’s add id and onclick using setAttribute(). We need to add texts inside the elements to make them visible. For that we can use innerHTML.

After everything, just append those elements to the list.

We added the onclick for those dynamically added elements but we need to add the function as well.

Let’s attach this code:


function remove(el) {
  var element = el;
  element.remove();
}

The code above in JSFiddle will return an error as we still need to define the variable i. I have added that so that I can have a number to attach while creating the new li elements. For e.g. Item 3, Item 4, etc.

Here is the code with i defined and incremented in function.

Now we are able to dynamically add and remove the li elements. Still, we can not remove the elements that predefined.

Let’s add the functions in the HTML that will delete those two elements on click as well.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

Forcing the domain to serve securely using HTTPSMiscHow to make a web page look good on any device?HTMLHow to change CSS with JavaScript?CSS10 Usability Blunders to AvoidUI/UXHow to Draw a Text Image using JavaScript?JavaScriptHow to add Read More Read Less Button using JavaScript?JavaScript