JQuery find first parent element with specific class prefix

JqueryJquery Selectors

Jquery Problem Overview


I want to get the first parent which has a specific class prefix, suppose:

<div class="div-a3332"> 
  <div class="div-a89892">
    <p>
      <div class="div-b2">
        <div id="divid">hi</div>
      </div>
    </p>
  </div>
</div>

For example, my current element is #divid and I want to find the first element that has the class prefix div-a. So basically it will select:

<div class="div-a89892">

  

Jquery Solutions


Solution 1 - Jquery

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Solution 2 - Jquery

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTime TravelView Question on Stackoverflow
Solution 1 - JqueryMatt BallView Answer on Stackoverflow
Solution 2 - JquerySunny R GuptaView Answer on Stackoverflow