admin管理员组

文章数量:1405370

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? e.g. find all parent,grandparent,grandgrand* of type LI from another LI ?

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? e.g. find all parent,grandparent,grandgrand* of type LI from another LI ?

Share Improve this question asked Aug 17, 2013 at 0:29 Roger JohanssonRoger Johansson 23.2k18 gold badges105 silver badges204 bronze badges 2
  • UL.find("li").each(... Or if you want a elements ultimately, UL.find("li a").each(.... Probably worth spending some time in the jQuery docs: api.jquery./category/traversing – user2437417 Commented Aug 17, 2013 at 0:35
  • If you find yourself using recursive methods with your jQuery selectors, you're probably doing it wrong (i.e less efficiently/easily than you could be) :) – nbrooks Commented Aug 17, 2013 at 0:38
Add a ment  | 

2 Answers 2

Reset to default 5

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.

本文标签: javascriptJQuery select all decendant li in ulStack Overflow