Leon Bogod Leon Bogod - 1 year ago 117
jQuery Question

How to delete specific li element in jQuery

I'm new to jQuery and I'm having trouble deleting a certain

element when you click on the
in the div. Instead of deleting the one next to the
it just deletes all of the
elements. Can someone please tell me what I'm doing wrong? Thanks.

$(function() {
$("#btn2").click(function() {
var toAdd = $("#listItem").val();
$("ol").append("<li>" + toAdd + "</li>");
$('ol').append('<div> X </div>')

$("#listItem").keydown(function(e) {
if (e.which === 13) {
e.preventDefault(); // Don't submit the form
$("ol").append("<li>" + this.value + "</li>"); // append this.value
this.value = ""; // reset the value field

$(document).on('dblclick', 'li', function() {
$(this).css("text-decoration", "line-through");;

$(document).on('click', ' div', function() {

Joe Joe
Answer Source

You are using a query selector to detect html elements by the tag name li. This is not a unique selector so it will return all the elements that match the query.

In the context of a click event, the this keyword will refer to the thing that has been clicked. You can use it to select the specific element if you know the html structure. I'm not sure from your question what your html looks like, but if it were as follows you could use this code. Note you can pass a second parameter to fadeOut as a callback function to be triggered once it has completed if you want to remove the li from the DOM instead of just hide it.




$(document).on('click', ' div', function() {
     $(this).closest('li').toggleClass('strike').fadeOut('slow', function() { $(this).remove(); });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download