I have an html page with a lot of nested elements. I'm trying to find the DOM distance between two nodes, so that I can select visual siblings even though they are not DOM siblings.
我有一个包含大量嵌套元素的html页面。我试图找到两个节点之间的DOM距离,这样我就可以选择可视兄弟,即使它们不是DOM兄弟。
<div class='root'>
<div class='wrapper'>
<div class='family brother'>
<div class='otherstuff'>Other Stuff</div>
</div>
</div>
<div class='wrapper'>
<div class='family sister'>
<div class='otherstuff'>More Stuff</div>
<div class='wrapper>
<div class='family nephew'>
<div class='otherstuff'>Yet more stuff</div>
</div>
</div>
</div>
</div>
</div>
So, with jQuery:
所以,使用jQuery:
var root = $(".root");
var siblings = root.find(".family");
But that will select brother, sister, and nephew.
但那将选择兄弟,姐妹和侄子。
I can't use
我不能用
var siblings = root.find(".wrapper>.family");
because that will also match all three.
因为这也将匹配所有三个。
And I can't use
我不能用
var siblings = $(".root>.wrapper>.family");
because there may be other wrapper elements depending on the template.
因为根据模板可能有其他包装元素。
What I'm looking for is: given .brother under .root, tell me if another .family is a "sibling" by calculating if the DOM (hierarchical) distance from .brother to .root matches the distance of another .family member from .root. The resulting set should contain only .brother and .sister, but not .nephew.
我正在寻找的是:在.root下给出.brot,通过计算从.brother到.root的DOM(分层)距离是否匹配另一个。家庭成员的距离,告诉我是否另一个.family是“兄弟姐妹” 。根。结果集应仅包含.brother和.sister,但不包含.nephew。
1 个解决方案
#1
2
This can be done by JQuery.closest()
这可以通过JQuery.closest()来完成
It will return the closest matching element from your target element.
它将返回目标元素中最接近的匹配元素。
Read the documentation here: http://api.jquery.com/closest/
阅读此处的文档:http://api.jquery.com/closest/
#1
2
This can be done by JQuery.closest()
这可以通过JQuery.closest()来完成
It will return the closest matching element from your target element.
它将返回目标元素中最接近的匹配元素。
Read the documentation here: http://api.jquery.com/closest/
阅读此处的文档:http://api.jquery.com/closest/