Yogesh Chauhan's Blog

How to add and remove list items using JavaScript?

in JavaScript on 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.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to convert a function component into a class in React?ReactAvoid using new Array() in JavaScriptJavaScriptHow to load a module with configuration in SCSS?SCSSCROSS JOIN in PostgresPostgresObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptSocial Media Colors: Sass VariablesMiscellaneous