简体   繁体   中英

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>

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM