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

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
SQL ALL OperatorSQL/MySQLForcing the domain to serve securely using HTTPSMiscellaneousReverse a String in JavaScriptJavaScriptFunction Scope in JavaScript for BeginnersJavaScriptLearn how to add Scroll Indicator using CSS and JavaScript?CSSHow to position an image on top of another image using CSS?CSS