Amir Saleem
Amir Saleem

Reputation: 3140

How to remove li on click of its child element

I am dynamically creating li with javascript, I want to add a close button to each li element created dynamically to delete the li element on click of the close button.This is my code so far:

   function addNew(){
    // get value from input field

    var taskName = document.getElementById('task-name').value;


    // innerHTML to be inserted inside li

    var fullText = taskName + '<span class = "close" onclick = 
   "addListener(this)">&times;</span>';


   // calling create function from Element object

   Element.createNew('li','className','tasks',0,fullText);
  }

  // remove function

   function addListener(e){
       e.parentNode.parentNode.removeChild(e.parentNode);
   }

The problem is the remove function removes the last li instead of li being clicked.

Here is the JSFiddle of the problem.

Upvotes: 0

Views: 122

Answers (1)

user6887261
user6887261

Reputation:

store all the list items in an array.

//suppose your list items have a class name 'lists'
//create a global var 
var lis = document.getElementsByClassName('lists');

initially it'll be empty, so in your add method(in which you're appending the new list item to ul, push the new list item in the lists array.

and in the addEvent(e) method , loop around every element in the lists array

function addEvent(e){
for(var i=0; i<lists.length; i++){
if(lists[i] === e){
//remove the lists element by using lists[i] instead of e
// and remember to pop the lists[i] and resize the lists array
}
}

Upvotes: 2

Related Questions