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;

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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create HTML elements with ID and class using JavaScript?HTMLWP_Query Class in WordPressWordPressHow to add a ribbon inside a container using CSS?CSSWhat is PostgreSQL? How similar or different it is from SQL?PostgresHow to deploy Angular App on Dreamhost or Amazon S3 or firebase?Angular5 Steps to Create a Line using Canvas Tag in HTML5HTML