Search code examples
jqueryclicktoggleclass

toggleClass on separate child elements


Im using the toggleClass method in a function like this:

JS

$('section .handle').click(function() {
    $('section h3 i').toggleClass('rotate');
});

HTML

<section>
    <ul>
        <li>
            <div class="handle clearfix">
                <h3>item one <i class="fa fa-arrow-down"></i></h3>
            </div>
            <ul class="panel">
                <li>lorem ipsum</li>
                <li>lorem ipsum</li>
                <li>lorem ipsum</li>
            </ul>
        </li>
    </ul>
</section>
<section>
    <ul>
        <li>
            <div class="handle clearfix">
                <h3>item two <i class="fa fa-arrow-down"></i></h3>
            </div>
            <ul class="panel">
                <li>lorem ipsum</li>
                <li>lorem ipsum</li>
                <li>lorem ipsum</li>
            </ul>
        </li>
    </ul>
</section>

now the problem is that i have several "i" elements and i need the class to be toggled on each single element, while like this the class is toggled on all of them.


Solution

  • Use this to reference to the clicked element and then simply find the <i> inside it.

    $('section .handle').click(function() {
        $("i", this).toggleClass('rotate');
    });