I am currently trying khổng lồ find the parent of a parent of an element. I have sầu a links being clicked that is in a , and I"d lượt thích lớn get the object.

Bạn đang xem: Jquery parent of a parent

Why wont "$(this).parent().parent()" work? What will?


Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest("tr")" because it seems lượt thích the most efficient solution.


The best way would probably be using closest:

$(this).closest("tr");Cheông xã out the documentation:

Closest works by first looking at the current element lớn see if it matches the specified expression, if so it just returns the element itself. If it doesn"t match then it will continue lớn traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.


It should work. You can also try $(this).parents(tag) , where tag is the tag you want khổng lồ find.

For example:

$(this).parents("tr:first")Will find the closest tr "up the chain".

Xem thêm: Php End Foreach Keyword - How To Break An Outer Loop With Php


That should work... you might try

$(this).parents(":eq(1)");The .parents(selector) says get all ancestors that match the selector

và the :eq(1) says find the oneth (zero-indexed, so the second) element in the list


This snippet has performed for me in the past:

$(this).parent().parent(); Post some code for us to see if there might be another problem somewhere...


If you have any sort of id/class for the parent, you can use parents() but that will give sầu you all parents up to the unless you filter() or stop it some other way like

$(this).parents(".myClass");Hope this helps someone :)

Try wrapping the $(this).parent() inlớn an jQuery object lượt thích $($(this).parent()) I often find the need to lớn vày this to lớn make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.

You can bởi vì parent of a parent và it"s very easy:

var parent = $(".myDiv").parent();var parentParent = $(parent).parent();var parentParentParent = $(parentParent).parent();etc.

Thanks for contributing an answer lớn Staông xã Overflow!

Please be sure to lớn answer the question. Provide details và cốt truyện your research!

But avoid

Asking for help, clarification, or responding lớn other answers.Making statements based on opinion; baông chồng them up with references or personal experience.

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree khổng lồ our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript jquery or ask your own question.

site thiết kế / hình ảnh © 2021 Stachồng Exchange Inc; user contributions licensed under cc by-sa. rev2021.3.5.38718