Jens Nielsen Jens Nielsen - 4 months ago 10
Javascript Question

call child elements inside parent on click from within parent

How do i call a parent element onclick inside the parent?

For example, i have multiple of these on a page

<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>


When i click the .some-btn i only whant it to happen for that .parent element, where the .some-btn is a child/clicked.

My jquery right now looks like this

$(".some-btn").click(function() {
$(".some-text").toggleClass("active",1000,"easeInOutQuad");
$(".some-image").toggleClass("active",1000,"easeInOutQuad");
$(".some-btn").toggleClass("active");
})


But this of course activates all .parent elements.

Answer

Select the parent element of the clicked element and then select inside this element:

$(".some-btn").click(function() {
    var that = $(this);
    var par = that.closest('.parent');
    par.find(".some-text").toggleClass("active",1000,"easeInOutQuad");
    par.find(".some-image").toggleClass("active",1000,"easeInOutQuad");
    that.toggleClass("active");
})
Comments