Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to recursively get the first parent of an element matched by a class filter

I have a situation in which i need a reference to the very next DIV that is the parent of my current DIV, but matches a specific class name.

<div class="container">
    <div class="something">test</div>
    <div class="something">test</div>
    <div class="something" onclick="$(use jquery to find parent with class container)">test</div>
</div>

This would be pretty easy, but it can also look like this:

<div class="container">
    <div class="someotherthing">
        <div class="something">test</div>
        <div class="something">test</div>
        <div class="something" onclick="$(use jquery to find parent with class container)">test</div>
    </div>
</div>

Which means that i am looking for a solution that recursively walks UP the dom until it finds a parent of a given element that matches a certain CSS class.

And i was wondering whether jQuery can do this in a one-shot call.

like image 624
SquareCat Avatar asked Dec 06 '22 18:12

SquareCat


2 Answers

The .closest() method should handle this:

 $(this).closest(".someclass")
like image 152
Kevin B Avatar answered Dec 10 '22 11:12

Kevin B


Take a look at jQuery closest method which get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

like image 44
ShankarSangoli Avatar answered Dec 10 '22 12:12

ShankarSangoli