First off, your markup was buggered. You were missing =
in the class attributes of the tr
elements. Clean markup makes the JS side of things a lot easier to manage. I would suggest you fix your markup, even refactor it to be more semantic (group data together into structures that make sense using elements like <dl>
or <ul>
).
Better html = less work.
Second, you were binding to body and the .delete
element. That's a lot of overhead in terms of event monitoring that jQuery has to do. It's unnecessary for the type of functionality you want to achieve. Bind only to elements that you want to track events on, use callbacks to handle related cases.
Lastly, there's absolutely nothing linking your <tr>
elements together that would indicate that those rows are related to the one you're attempting to delete. So, your script was deleting only the one row. You can use data-attributes
and other element attributes to link your target elements together. I updated your fiddle to show you what I mean. Your Updated Fiddle...
Here's the revised jQuery script:
jQuery( function(){
$('.delete').click( function(){
var obj = $( this ); // your delete link
var table = obj.closest('table'); // the containing table
var trgroup = obj.attr('data-group'); // a data-attribute that links your other elements together
if( trgroup ) // If the attribute is available continue...
{
console.log( table.find('tr[rel="' + trgroup + '"]') );
// Find all related element and remove them.
table.find('tr[rel="' + trgroup + '"]').empty().remove();
}
// Remove the table row of the executing link and it's children.
obj.closest('.itemRow').empty().remove();
});
} );
I'll probably catch a little flack for using empty().remove() instead of just .remove(), but that's my own preference.