EverTheLearner
EverTheLearner

Reputation: 7210

Add a close event button to every <li> in an <ul>

I would like to add an x button to every <li> I have in my <ul>. This x (close) button will delete that individual <li> from the <ul>. How do I do this using jQuery to create a single function that takes the this to delete the current item?

Heres my example HTML:

<ul id="list_a">
  <li value="1">Red&nbsp;&nbsp;<span class="closeButton">X</span></li>
  <li value="2">Orange&nbsp;&nbsp;<span class="closeButton">X</span></li>
  <li value="3">Green&nbsp;&nbsp;<span class="closeButton">X</span></li>
</ul>

edit: added close button <span>

Upvotes: 1

Views: 3717

Answers (3)

Andy
Andy

Reputation: 30135

I would also create the close Buttons dynamically with jQuery.

$('#list_a li').each(function(){
    $(this).append($('<span/>',{html:'X',class:'closeButton'}).click(function(){
        $(this).parent().remove();
    }));
});

Upvotes: 1

Gabe
Gabe

Reputation: 50523

// Use live to bind click event to each element with closeButton class and remove it
$('.closeButton').live('click', function(){
    $(this).parent().remove();
});

<ul id="list_a">
   <li value="1">Red&nbsp;&nbsp;<span class="closeButton">X</span></li>
   <li value="2">Orange&nbsp;&nbsp;<span class="closeButton">X</span></li>
   <li value="3">Green&nbsp;&nbsp;<span class="closeButton">X</span></li>
</ul>

jsFiddle

Upvotes: 2

Dennis
Dennis

Reputation: 32608

Event delegation. Select the list, then ask it to listen to click events on the .closeButtons. Then remove the li or the parent of the span.

$("#list_a").delegate(".closeButton", "click", function() {
    $(this).parent().remove();
});

Upvotes: 1

Related Questions