简体   繁体   中英

JQuery select all decendant li in ul?

If I have an hierarchical UL / LI list, is it possible to fetch all decendant LI's from the root UL using JQuery?

Currently I do recursion from within UL.children('li').each(...)

(function foo($ul) {
    $ul.children("li").each(function () {
        var $li = $(this);
        tabMap[$li.find('a').attr('href')] = $li;
        $li.children("ul").each(function () {
            foo($(this));
        });
    });
})($ul);

Which works fine, but I it would be nice if it was possible to do this in one go so to say.

Also, would it be possible to do the same but for parents? eg find all parent,grandparent,grandgrand* of type LI from another LI ?

You can get all the descendent UL elements with .find() :

$ul.find("li")

You can get all the ancestors with .parents() :

$li.parents("li");

You can find all the jQuery tree traversal methods here .

To collect all href's of anchor links which are direct children of list-items within some root list, start from the root, find all such links, then put them in the map and associate them with their parent.

var tabMap = {};
$("ul#root").find("li > a").each(function() {
    var link = $(this).attr("href");
    var $li = $(this).parent("li");
    tabMap[link] = $li;
});

Note that the filter parameter in the call to parent isn't necessary, but it helps make it clear what you're expecting to find there. Additionally ul#root is overly-specific since the ID is unique; I only added the ul here to make it obvious that this is your top-level list, and you should put the correct for that element based on your HTML.

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