[javascript] How to find a parent with a known class in jQuery?

I 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 d and I want to find the ID for its parent, class a, how would I do this?

I cannot simply do $('.a').attr('id');, because there are multiple class as. 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 class c).

This question is related to javascript jquery html dom parent

The answer is


Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.

$(this).parent().closest('.a');

Thanks


Pass 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.


<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.


You 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.

jQuery parent() vs. parents()

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.


Use .parentsUntil()

$(".d").parentsUntil(".a");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to parent

parent & child with position fixed, parent overflow:hidden bug How can I return to a parent activity correctly? How to call a parent method from child class in javascript? Make div (height) occupy parent remaining height jQuery: get parent tr for selected radio button Select parent element of known element in Selenium fork() child and parent processes How do I get the n-th level parent of an element in jQuery? How to delete parent element using jQuery PHP Accessing Parent Class Variable