Roger Johansson
Roger Johansson

Reputation: 23224

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

Upvotes: 0

Views: 5166

Answers (2)

nbrooks
nbrooks

Reputation: 18233

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.

Upvotes: 1

Barmar
Barmar

Reputation: 782693

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.

Upvotes: 5

Related Questions