jQuery remove list item onclick

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

Lets add couple of list elements with id and a button with id.

Now, lets 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.

Lets 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.

Lets 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.

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


attributes create elements html tags list
Share this post
« Previous Next »