TurboSupra
TurboSupra

Reputation: 119

Removing jQuery UI Accordion

I am utilizing the jQuery UI, the accordion specifically. I wanted to add a "remove" button to each accordion that would hide it.

My current code just sets the visibility to hidden on the div. But, I need to completely remove the accordion.

Here is how I have my html laid out.

<div class="my-accordion">
    <h3>Accordion 1</h3>
    <div>
        <p>derp</p>
        <div class="remove">REMOVE</div>  
    </div>
    <h3>Accordion 2</h3>
    <div>
        <p>derp</p>
        <div class="remove">REMOVE</div>  
    </div>
    <h3>Accordion 3</h3>
    <div>
        <p>derp</p>
        <div class="remove">REMOVE</div>  
    </div>
</div>

And, here is my jQuery.

$(function() {
    $( ".my-accordion" ).accordion();
});

// This is a giant failure.
$('.remove').click(function(e) {
        $(this).parent().hide();
        e.preventDefault();
});

Upvotes: 0

Views: 2363

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

$('.remove').click(function(e) {
    var parent = $(this).parent('div');
    parent   // parent div of REMOVE
      .prev('h3') // catch previous h3
      .andSelf()  // parent div
      .remove();  // remove both parent div and h3
});

DEMO

To remove the parent div use .remove().

OR in a row

$('.remove').click(function(e) {
    $(this).parent('div').prev('h3').andSelf().remove();
});

DEMO

Note

It would be better if you can wrap each accordion within a div wrapper like below:

HTML

<div class="my-accordion">
    <div class="accordion-wrapper">
       <h3>Accordion 1</h3>
       <div>
        <p>derp</p>
        <div class="remove">REMOVE</div>  
       </div>
     </div>
    .....
</div>

and change the jQuery code like:

$('.remove').click(function(e) {
    $(this).parents('div.accordion-wrapper').remove();
});

Upvotes: 1

Related Questions