Genic
Genic

Reputation: 193

Get parent div recursively

I have this HTML

<div id="main-container">
   <div style="style-here" data-status="active" data-state="loaded">
      <div style="style-here">
         <div style="style-here" {{click_event}}></div>
      </div>
   </div>
   <div style="style-here" data-status="active" data-state="unloaded">
      <div style="style-here">
         <div style="style-here" {{click_event}}></div>
      </div>
   </div>
   <div style="style-here" data-status="inactive" data-state="unloaded">
     <div style="style-here">
         <div style="style-here" {{click_event}}></div>
      </div>
   </div>
</div>

On click on one of the elements that has {{click_event}} I want to search recursively till I can find an element that has data-status or data-state, and in the worst case when I meet the id from top to stop de search.

The HTML is made generated from another JS file and I can't change the way is made it. Is there a way with closest or parent from jQuery to search after data attribute?

Thank you.

Upvotes: 0

Views: 120

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

No need for recursion, you can use closest():

$clickedElement.click(function() {
    var $parent = $(this).closest('[data-status], [data-state], #main-container');
});

Upvotes: 4

Related Questions