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 wanta
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
2 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - JQuery select all decendant li in ul? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744895853a2631058.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论