Search code examples
jqueryparent

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


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')


Solution

  • 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.