Note that the number of parent elements may vary. It could be just one or multiple.
I'm experimenting with different methods to locate the outermost parent <div>
element that contains a <div>
element with the class rat
along with a label. In this scenario, the top-level <div>
should be retrieved.
<div> --> Should be returned
<div>
<div class="item box1" id="box1">1</div>
<div class="item" id="box2">2</div>
<div class="item" id="box3">3</div>
<div class="item rat" id="box4">4</div>
</div>
<label>I am the original parent</label>
</div>
Adding class attributes to each <div>
and using closest()
works well for many cases, but in this instance, there is no single unique selector that fits.
Alternatively, we can approach it by finding the nearest label element to the <div>
with the class rat
, as shown in the example above:
$('.rat') -> selector