When I click the class “red” I want to delete this entire div. My JS is
$('document').ready(function(){
$('.buttons .red').click(function(){
$(this).parent('div').parent('div').remove();
$(this).parent('div').remove();
});
});
Here is my HTML
<div data-role="collapsible" data-collapsed="false">
<h3> Keep</h3>
<div id= "container">
<a href="categories.html" class="green" data-transition="slide" data-type="horizontal" data-role="button">Tax Deductible</a>
<a href="#" class="red" data-transition="slide" data-type="horizontal" data-role="button">Tax Deductible</a>
<a href="categories.html" class="blue" data-transition="slide" data-type="horizontal" data-role="button">Tax Deductible</a>
</div>
</div>
I’d suggest:
JS Fiddle demo.
This attaches the click event to an
aelement who has thedata-roleattribute with the value ofbutton, and also the class ofred.The default behaviour of the
clickevent is prevented (to preventhashChange, or page-jumping/loading), the selector moves up the DOM from theaelement to the first ancestor element with thedata-roleattribute set and removes that element.The use of
closest()means you can nest theaelement inside of other elements (within the same ancestor), and the function will still work (whereas withparent().parent()...you’d have to rewrite the jQuery selector every time an ancestor was inserted/removed.References:
[attribute="value"]selector.closest().event.preventDefault().remove().