JQuery find first parent element with specific class prefix

Time Travel picture Time Travel · Sep 17, 2011 · Viewed 147.8k times · Source

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

Answer

Matt Ball picture Matt Ball · Sep 17, 2011

Use .closest() with a selector:

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