Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Adding and) Removing list items with JavaScript / jQuery

I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).

Here is the thing. I have a list with lots of stuff in each list item:

<ul id="fruit_list">
    <li>
         <h4> Fruit 1: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>

    <li>
         <h4> Fruit 2: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>
</ul>

<a href="#" class="add">add</a>

What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.

(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)

So here is what I've written so far:

$(function(){
    var i = $('#fruit_list li').size() + 1;

    $('a.add').click(function() {
        $('<li><h4>Fruit '+i+':<a href="#" class="remove">
             remove</a></h4><p>Blabla</p></li>')
        .appendTo('#fruit_list');
        i++;
    });

    $('a.remove').click(function(){

        $(this).parentNode.parentNode.remove();
        /* The above obviously does not work.. */
        i--;
    });
});

The 'add' anchor works as expected. The 'remove' drinks a lemonade..

So, any ideas? Thanks

EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:

$('a.remove').live('click', function(){
    $(this).closest('li').remove();
    i--;
});

Thank you for your rapid help!

like image 528
Mpampirina Avatar asked Apr 30 '26 03:04

Mpampirina


1 Answers

The a.remove event binding needs to be a live http://api.jquery.com/live/ binding. The nodes are added to the DOM after doc ready is called.

Additionally, I think you want to use parent() instead of parentNode. Unless I'm behind on my jQuery, parentNode is just DOM manipulation and there's no standard remove(), it's removeChild(). Here you need a jQuery collection returned from parent().

like image 72
Travis Avatar answered May 02 '26 16:05

Travis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!