How to add a class to the overarching class above of 'this' in jquery

79 views Asked by At

My html is set up like so:

<div class="containerElement">
    <div class="element"></div>
</div>
<div class="containerElement">
    <div class="element"></div>
</div>

whenever a ".element" is clicked I want to add a class to the element's ".containerElement" and only that one instance of "containerElement".

How do I add a class to that one instance of "containerElement" in javascript whenever an element is clicked, my jquery code thus far is:

$('.element').click(function(){
    $('.containerElement', this).addClass('highlighted');
})

what is the correct syntax in stead of "$('.containerElement', this)"

2

There are 2 answers

3
Tomzan On

You can do it by referring to the direct parent of the click event target.

$('.element').click(function() { 
    $(this).parent().addClass('highlighted');
})
0
Tushar On

You can use closest to get the closest ancestor with the class and siblings to get it's sibling elements.

$(this).closest('.containerElement').addClass('highlighted').siblings().removeClass('highlighted');