Question

I am having an issue removing/adding a class to the closest div with a class. Right now it toggles the class for all, and not for the closest.

What am I doing wrong?

$(document).on('click', '.btnMoreInfo', function () { 
$(this).closest('div').find('.moreInfo').toggleClass('hide')
})

HTML:

<ul>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>
<li>
    <button class='btnMoreInfo'>More</button>
    <div class='moreInfo hide'></div>
</li>

Was it helpful?

Solution

One way would be to use jQuery's next() method (assuming your HTML structure always looks like it does above):

$(document).on('click', '.btnMoreInfo', function () { 
  $(this).next('div').toggleClass('hide');
})

jsFiddle example here.

OTHER TIPS

$(this).next('.moreInfo').toggle();

you can also use slideIn and slideOut and toggle

you can use next like

$(this).next('.moreInfo').toggleClass('hide');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top