Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - search upwards for an element with a certain class?

Tags:

jquery

parent

Is there a way in jquery to target $(this).some element above it.with class of 'abc'

(by above, I mean parent, grandparent etc.)

for example:

<div class='a'>
    <div class='b'>
        <div class='c'>
        </div>
    </div>
</div>

So when I click on class='c', Can i target anything above it with class='a', and get the same result as if I clicked class='b' with the same code? (if I click 'b', the 'a' div will still be its parent (or grandparent) with class of 'a')

like image 600
d-_-b Avatar asked Dec 12 '22 23:12

d-_-b


1 Answers

Try closest() :

$(this).closest('.a')

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

like image 131
adeneo Avatar answered Mar 08 '23 22:03

adeneo