Finding parent row of form text input Finding parent row of form text input jquery jquery

Finding parent row of form text input


internally, jquery uses .closest for this kind of stuff.

var listItemId = $(this).closest('tr').attr('data-id');

moreover if you have nested tables (which I never saw, but we never know), you have to select the first 'tr' too. (it's more useful with looking for divs than rows though). However, for code unification, I never use parents when I need closest. That way, the function names implies it's meaning exactly (closest parent), while .parents() leaves more room to interpretation, and thus reduce code readability (imo)

performance wise, they are equivalent (check this jsperf )

finally, you can consider a pure javasrcipt approache too: parentNode (by miles faster than anything else, if you really need speed)

in your case:

var listItemId = $(this.parentNode.parentNode).attr('data-id');

or

var listItemId = this.parentNode.parentNode.attributes['data-id'].value;

NB: pure javascript methods need valid html to work, unlike the one in your question (close your input tag, and add a table one).

here is a little fiddle


try

var listItemId = $(this).parents('.list-item').attr('data-id');

parents() goes up in the tree until it matches the selector


I would suggest:

var listItemId = $(this).parents('tr').data('id');

The class selector is the slowest of all the jQuery selectors and should avoided unless there is no other way to go the information you need.

UPDATE

I fixed the syntax to make use of the .data() method correctly. This way only works in version 1.4.3 or higher.