Stiño
Stiño

Reputation: 2853

How to select only one li element using javascript?

This should be an easy fix but I just can't wrap my head around javascript selectors just yet. I have a list of h3 li elements that each contain content that is shown on click. I want a toggle arrow to change from up to down on click. But with the JS code below this happens for all li elements including the one for which the collapsed content is not showing. How can I fix this?

$(document).ready(function () {

$('#toggle-view li').click(function () {
    var text = $(this).children('div.panel');
    if (text.is(':hidden')) {
        text.slideDown('200');
        $("h3 .fa-caret-up").removeClass("fa-caret-up").addClass("fa-caret-down");
    } else {
        text.slideUp('200');
        $("h3 .fa-caret-down").removeClass("fa-caret-down").addClass("fa-caret-up");
    }

});
});

Here is the html in case you need it:

<ul class="services-ul facebook-ul" id="toggle-view">
        <li>
        <h3><i class="fa fa-check"></i>Header 1<i class="fa fa-caret-up"></i></h3>
                <span>+</span>
                <div class="panel">
                    <p>dummy text...</p>
                </div>
        </li>
        <li>
        <h3><i class="fa fa-check"></i>Header 2<i class="fa fa-caret-up"></i></h3>
                <span>+</span>
                <div class="panel">
                    <p>dummy text...</p>
                </div>
        </li>
        <li>
        <h3><i class="fa fa-check"></i>Header 3<i class="fa fa-caret-up"></i></h3>
                <span>+</span>
                <div class="panel">
                    <p>dummy text...</p>
                </div>
        </li>
        <li>
        <h3><i class="fa fa-check"></i>Header 4<i class="fa fa-caret-up"></i></h3>
                <span>+</span>
                <div class="panel">
                    <p>dummy text...</p>
                </div>
        </li>
    </ul>

Upvotes: 1

Views: 1966

Answers (1)

James Donnelly
James Donnelly

Reputation: 128781

You need to specify the elements relative to this (which within your click event is the li element which has been clicked on).

Simply wrap this in a jQuery selector ($(this)), then use jQuery's find() method to find the elements contained within it:

$(this).find('.fa-caret-up').removeClass('.fa-caret-up').addClass('.fa-caret-down');

And:

$(this).find('.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-up');

Upvotes: 1

Related Questions