- This topic is empty.
- AuthorPosts
-
March 17, 2011 at 12:29 pm #11052
abctest483MemberI have a
<div>that has many other<div>s within it, each at a different nesting level. Rather than give every child<div>an identifier, I rather just give the root<div>the identifier. Here’s an example:<div class="a" id="a5"> <div class="b"> <div class="c"> <a class="d"> </a> </div> </div> </div>If I write a function in jQuery to respond to class
dand I want to find the ID for its parent, classa, how would I do this?I cannot simply do
$('.a').attr('id');, because there are multiple classas. I could find its parent’s parent’s parent’s ID but that seems of poor design, slow, and not very polymorphic (I would have to write different code for finding the ID for classc).March 17, 2011 at 12:30 pm #11057
abctest483MemberPass a selector to the jQuery parents function:
d.parents('.a').attr('id')EDIT Hmm, actually Slaks’s answer is superior if you only want the closest ancestor that matches your selector.
March 17, 2011 at 12:31 pm #11058
abctest483MemberAssuming that
thisis.d, you can write$(this).closest('.a');The
closestmethod returns the innermost parent of your element that matches the selector.March 17, 2011 at 12:33 pm #11055
abctest483MemberYou can use parents() to get all parents with the given selector.
Description: Get the ancestors of each
element in the current set of matched
elements, optionally filtered by a
selector.But parent() will get just the first parent of the element.
Description: Get the parent of each
element in the current set of matched
elements, optionally filtered by a
selector.And there is .parentsUntil() which I think will be the best.
Description: Get the ancestors of each
element in the current set of matched
elements, up to but not including the
element matched by the selector.July 23, 2018 at 5:49 am #11053
abctest483MemberUse .parentsUntil()
$(".d").parentsUntil(".a");May 26, 2020 at 11:34 am #11056
abctest483MemberExtracted from @Resord’s comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');Thanks
November 2, 2020 at 1:31 am #11054
abctest483Member<div id="412412412" class="input-group date"> <div class="input-group-prepend"> <button class="btn btn-danger" type="button">Button Click</button> <input type="text" class="form-control" value=""> </div> </div>In my situation, i use this code:
$(this).parent().closest('.date').attr('id')Hope this help someone.
- AuthorPosts
- You must be logged in to reply to this topic.