简体   繁体   中英

Selecting all children and decendants with jQuery

I have some HTML that is being produced by a WordPress plugin that is designed to allow for expandable/collapsible text, with up to three levels of depth. I would like it so that if you were to collapse the first or second levels and the children below it were also expanded those too would get collapsed but nothing I use seems to allow the selection of all children. This is what I'm using so far:

$(".hidden-text-toggle").click(function () {
    if ($(".hidden-text:animated").length) return false;
        $(this).next().slideToggle();
        if ($(this).hasClass('expanded') ){     
            $(this).removeClass('expanded');
            $(this).animate({ backgroundColor: "black" , color: "red"});    
        }
        else
        {
            $(this).addClass('expanded');
            $(this).animate({backgroundColor: "red" , color: "black"});

        }
        return false;
    });

<div class="wrapper">
    <h2 class="title">Level One</h2>
    <div class="text" href="#">
        This is level one text.
        <div class="wrapper">
            <h2 class="title" href="#">Level Two</h2>
            <div class="text">
                This is level two text.
                <div class="wrapper">
                    <h2 class="title" href="#">Level Three</h2>
                    <div class="text">                          
                        This is level three text. 
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

I would have thought that putting something like $(this).find(".text").slideUp(); after line 4 would allow this but apparently I am wrong.

Any help would be much appreciated!

You can just do a blanket slideUp on every element (do this in combination with find ):

$("div.wrapper").find("div").slideUp();

Note that this is essentially selecting every div underneath the root node, then animating the height of each to zero. Any elements that are already zero height will not be affected.

Try:

$("h2.title").click(function () {
    $(this).next().slideToggle();
});​

Fiddle: http://jsfiddle.net/iambriansreed/amppK/

Docs: http://api.jquery.com/toggle-event/

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