jabeoogie jabeoogie - 2 months ago 6
Javascript Question

When using a jQuery delegated event handler, how do I get the descendant selector?

When using a jQuery delegated event handler, how do I get the descendant selector? For example, in the following table, I want to select the table row that was clicked:

<div id='timeline'>
<table>
<tr data-somedata=5><td>First Row</td></tr>
<tr data-somedata=100><td>Another row</td></tr>
</table>
</div>


The table is added dynamically, so I'm using a delegated event handler.

$("#timeline").on('click', $("tr"), function(event){
console.debug($(this)); // This selects the entire #timeline
console.debug(event.target); // This selects the <td> element, not the <tr>
});


How can I select the tr element using the above delegated event handler?

Also, if someone has a JavaScript only solution, that would be great too.

Answer

I put the solution (that I mentioned in comment section) to helping future readers.

You passed jQuery object as selector, you need to change the code to following, then $(this) will be the tr:

$('#timeline').on('click', 'tr', function(event){
    var $tr = $(this);

    // play with $tr
});

More about on here: .on()

Comments