0

I have this simple html code:

<ul>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
</ul>

and my javascript function:

function test() {
    // do something
}

Now, if I clicked on a button I would like to remove the whole

  • element of the button, which was clicked. Can you show me how? :/

    With "remove" I mean

    $(selector).toggle( "slide" );
    
  • Trombone0904
    • 4,132
    • 8
    • 51
    • 104

    2 Answers2

    0

    First, avoid inline handlers - they're inelegant, tedious to work with, and have way too many problems to be worth using nowadays. Attach event listeners properly using Javascript with addEventListener or jQuery instead.

    Iterate over all the buttons and add a listener to each. When clicked, navigate to the button's parent and call .toggle('slide') on it:

    $('button').on('click', function() {
      $(this).parent().toggle( "slide" );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
       <li>
          <button>Button</button>
       </li>
       <li>
          <button>Button</button>
       </li>
       <li>
          <button>Button</button>
       </li>
    </ul>
    CertainPerformance
    • 356,069
    • 52
    • 309
    • 320
    0

    It's generally not a good idea to use inline event handlers.

    Instead, you can easily attach an event handler to all buttons in jQuery like:

    $('ul button').click(function(){
      $(this).closest('li').toggle( "slide" );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
       <li><button>Button 1</button></li>
       <li><button>Button 2</button></li>
       <li><button>Button 3</button></li>
    </ul>

    In case, you still want to use inline event handlers then you can simply pass this inside the handler like:

    <button onclick="test(this)">Button</button>
    

    and update your javascript function like:

    function test(obj) {
        $(obj).closest('li').toggle("slide");
    }
    

    Demo:

    function test(obj) {
      $(obj).closest('li').toggle("slide");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li><button onclick="test(this)">Button 1</button></li>
      <li><button onclick="test(this)">Button 2</button></li>
      <li><button onclick="test(this)">Button 3</button></li>
    </ul>
    palaѕн
    • 72,112
    • 17
    • 116
    • 136