More efficient way to do parent().parent().parent() etc. in jquery

I think .closest() is what you're looking for :)


You have 2 nested tables,
to get what you want you can use this two DOM traversal methods .closest() or .parents()

  • .closest() Self or ancestor. Self or travels up the DOM tree until it finds a match for the supplied selector
  • .parents() Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied

Using nested tables:

$(this).closest('table').closest('tbody').attr('id');

$(this).parents('table').parents('tbody').attr('id');

jsFiddle demo

Tags:

Jquery