wondergoat77
wondergoat77

Reputation: 1815

Remove clicked <li> onclick

I have this JavaScript code:

window.onload = init;

function init () {
    var button = document.getElementById("submitButton");
    button.onclick = addItem;
    var listItems = document.querySelectorAll("li");  //assigning the remove click event to all list items
    for (var i = 0; i < listItems.length; i++) {
        listItems[i].onclick = li.parentNode.removeChild(li);
    }
}

function addItem() {
    var textInput = document.getElementById("item");  //getting text input
    var text = textInput.value;   //getting value of text input element
    var ul = document.getElementById("ul");  //getting element <ul> to add element to
    var li = document.createElement("li");  //creating li element to add
    li.innerHTML = text;    //inserting text into newly created <li> element

    if (ul.childElementCount == 0) {  //using if/else statement to add items to top of list
        ul.appendChild(li);       // will add if count of ul children is 0 otherwise add before first item
    }
    else {
        ul.insertBefore(li, ul.firstChild);
    }
}

function remove(e) {
    var li = e.target;
    var listItems = document.querySelectorAll("li"); 
    var ul = document.getElementById("ul");
    li.parentNode.removeChild(li);        
}

and this HTML:

<body>
     <form>
         <label for="item">Add an item: </label>
          <input id="item" type="text" size="20"><br>
         <input id="submitButton" type="button" value="Add!">
     </form>
     <ul id="ul">
     </ul>
     <p>
         Click an item to remove it from the list.
    </p>  
</body>

What I want to do is remove the whichever <li> element the user clicks, but this doesn't seem to be working and I am unable to find an answer anywhere else online for this specific scenario. Hoping someone can help me out here and show me what i am missing.

Upvotes: 16

Views: 49979

Answers (6)

mplungjan
mplungjan

Reputation: 177960

UPDATE

Plain JS delegation

Add the eventListener to the UL to delegate the click even on dynamically inserted LIs:

document.getElementById("ul").addEventListener("click",function(e) {
  var tgt = e.target;
  if (tgt.tagName.toUpperCase() == "LI") {
    tgt.parentNode.removeChild(tgt); // or tgt.remove();
  }
});

jQuery delegation

$(function() {
  $("#submitButton").on("click",function() {
    var text = $("#item").val();   //getting value of text input element
    var li = $('<li/>').text(text)
    $("#ul").prepend(li); 
  });
  $("#ul").on("click","li",function() {
    $(this).remove();
  });
});   

Original answer

Since you did not mention jQuery

var listItems = document.getElementsByTagName("li"); // or document.querySelectorAll("li"); 
for (var i = 0; i < listItems.length; i++) {
  listItems[i].onclick = function() {this.parentNode.removeChild(this);}
}

you may want to wrap that in

window.onload=function() { // or addEventListener
  // do stuff to the DOM here
}

Re-reading the question I think you also want to add that to the dynamic LIs

li.innerHTML = text;    //inserting text into newly created <li> element
li.onclick = function() {
  this.parentNode.removeChild(this);
   // or this.remove(); if supported
}

Here is the complete code as I expect you meant to code it

Live Demo

window.onload=function() {
  var button = document.getElementById("submitButton");
  button.onclick = addItem;
}   

function addItem() {
  var textInput = document.getElementById("item");  //getting text input
  var text = textInput.value;   //getting value of text input element
  var ul = document.getElementById("ul");  //getting element <ul> to add element to
  var li = document.createElement("li");  //creating li element to add
  li.innerHTML = text;    //inserting text into newly created <li> element
  li.onclick = function() {
    this.parentNode.removeChild(this);
    // or this.remove(); if supported
  }
  if (ul.childElementCount == 0) {  //using if/else statement to add items to top of list
    ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
  }
  else {
    ul.insertBefore(li, ul.firstChild);
  }
}

In case you want to use jQuery, the whole thing gets somewhat simpler

Live Demo

$(function() {
    $("#submitButton").on("click",function() {
        var text = $("#item").val();   //getting value of text input element
        var li = $('<li/>')
          .text(text)
          .on("click",function() { $(this).remove()});
        $("#ul").prepend(li); 
    });
});   

Upvotes: 33

Uday Hiwarale
Uday Hiwarale

Reputation: 4157

If you don't want to write function in javascript, you can use immediately invoked anonymous function like below...

<elem onclick="(function(_this){_this.parentNode.removeChild(_this);})(this);"

Upvotes: 3

user2878805
user2878805

Reputation:

I know you already received an answer, but back to your original remove function. You have the following:

function remove(e) {
    var li = e.target;
    var listItems = document.querySelectorAll("li"); 
    var ul = document.getElementById("ul");
    li.parentNode.removeChild(li);        
}

Change it to this and you should get what you were trying to achieve:

function remove(e)
{
   var li = e.target;
   var ol = li.parentElement;
   ol.removeChild( li);
   return false;
}

Upvotes: 5

David Thomas
David Thomas

Reputation: 253318

I'd suggest simplifying things a little:

Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

var lis = document.querySelectorAll('li');

for (var i = 0, len = lis.length; i < len; i++) {
    lis[i].addEventListener('click', remove, false);
}

JS Fiddle demo.

Of course, having done the above, I'd then have to go further (possibly because I like jQuery too much) and also:

Object.prototype.on = function (evt, fn) {
    var self = this.length ? this : [this];
    for (var i = 0, len = self.length; i < len; i++){
        self[i].addEventListener(evt, fn, false);
    }
};
Object.prototype.remove = function(){
    var self = this.length ? this : [this];
    for (var i = 0, len = self.length; i < len; i++){
        self[i].parentNode.removeChild(self[i]);
    }
};

document.querySelectorAll('li').on('click', remove);

JS Fiddle demo.

Upvotes: 4

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12042

The answer is more obvious than it could seem, you forgot to add init() in your script, is normal that the click event aren't triggered, they're not set on the element!

EDIT:

Your code has some logical errors. If you don't add an onclick function for all those created elements you will not be able to remove the clicked element. This is because the function init() is called one time at the load of the page!

function init() {
    var button = document.getElementById("submitButton");
    button.onclick = function() {addItem()};
}

function addItem() {
    var textInput = document.getElementById("item"); //getting text input
    var text = textInput.value; //getting value of text input element
    var ul = document.getElementById("ul"); //getting element <ul> to add element to
    var li = document.createElement("li"); //creating li element to add
    li.innerHTML = text; //inserting text into newly created <li> element
    li.onclick = function() {this.parentNode.removeChild(this);}

    if (ul.childElementCount == 0) { //using if/else statement to add items to top of list
        ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
    } else {
        ul.insertBefore(li, ul.firstChild);
    }
}
init();

Upvotes: 0

mishik
mishik

Reputation: 10003

If I understood you correctly:

$("li").on("click", function() {
  $(this).remove()
});

Upvotes: 1

Related Questions