I have the following function:
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
When a user clicks on a td element in a table it adds the row_selected class to the row. However when a user clicks on an input element inside of a td then it adds the row_selected class to the td.
Is there a way that I can change event.target.parentNode so that instead of the parent it adds the class to the parent tr?
I have the following function:
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
When a user clicks on a td element in a table it adds the row_selected class to the row. However when a user clicks on an input element inside of a td then it adds the row_selected class to the td.
Is there a way that I can change event.target.parentNode so that instead of the parent it adds the class to the parent tr?
Share Improve this question edited Jul 22, 2012 at 18:22 Lee Taylor 7,98416 gold badges37 silver badges53 bronze badges asked Jul 22, 2012 at 18:16 user1464139user14641394 Answers
Reset to default 7Use closest()
.
$(event.target).closest('tr').addClass('row_selected');
Change your handler to use jQuery's event delegation instead of your own...
$("#example tbody").on("click", "tr", function(event) {
...then you can just use this
...
$(this).addClass('row_selected');
You can use parentsUntil() function, that is sort of like finding ancestors. I cant remember the function for ancestors, but this will work:
$(event.target).parentsUntil("tr").addClass('row_selected');
you can try this
$(event.target).closest('tr').addClass('row_selected');
Instead of your line
$(event.target.parentNode).addClass('row_selected');
Using closest(), you will be able to apply row_selected
class to nearest tr
element of the element you click, that may be a td
or any other element inside it.