Heraclitus Heraclitus - 5 months ago 11
jQuery Question

Add functionality to first button in list only

My HTML (stripped down)

<ul>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
</ul>


My JavaScript

$('body').on('click', 'li > button', function() {
$(this).parent().remove();

if($('li > button').length === 1) { // if this is the only button
$(this).parent().parent().remove(); // remove whole list
// remove some other elements outside the list
}

if($(this).parent().is(':first')) { // if this first li in ul
if (confirm("...")) {
$(this).parent().remove();
}
}
});


Basically, what I'm trying to do is:


  • Make first button to remove the parent list item

  • If the button is the only one in the
    <ul>
    remove the whole list and another element



How can I correctly make this work?

Answer

Change your function to check if the last <li> was removed (read: the <ul> has no more <li>):

$('body').on( 'click', 'li > button', function() {
    var list = $(this).closest( 'ul' );

    $(this).parent().remove()

    //* if the UL is empty we can remove it altogether
    if( list ).find( 'li' ).length == 0 ) remove( list ); 
});