estevan gomez estevan gomez - 6 months ago 10
jQuery Question

jQuery toggle a class existent above the clicked function

I have multiple instances of the HTML below:

<div class="col-md-4">
<div class="widget">
<div class="widget-head">
<a class="collapse" href="#"><i class="fa fa-arrow-circle-down" aria-hidden="true"></i></a>
<span>Title</span>

<a href="#"><i class="fa fa-expand icon-spacer" aria-hidden="true" onclick="dosomething();"></i></a>
</div>
</div>
</div>


jQuery:

function dosomething() {
.widget above toggleClass('someClassHere');
}


I need to be able to click on
dosomething
and have a
class
toggled (added), to the nearest
.widget
above it.

How can I do this in
jQuery
?

Answer

You can use closest method of jQuery.

<a href="#"><i class="fa fa-expand icon-spacer" aria-hidden="true" onclick="dosomething(this);"></i></a>

function dosomething(obj) {
    $(obj).closest('.widget').toggleClass('someClassHere');
}