YogeshChauhan . com

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 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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is the best way to add JavaScript Code into HTML?HTMLaddcslashes() and addslashes() String Functions in PHPPHPHow to select an element using its ID without the high specificity of the ID selector?CSSLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHP4 ways to create Date Objects in JavaScriptJavaScriptWordPress: How to loop through a repeater field in ACF?WordPress