在jQuery中选择最深的子项 [英] select deepest child in jQuery
问题描述
有一种cheep方法来选择元素的最深子?
示例:
< div id =SearchHere>
< div>
< div>
< div>< / div>
< / div>
< / div>
< div>< / div>
< div>
< div>
< div>
< div id =selectThis>< / div>
< / div>
< / div>
< / div>
< div>
< div>< / div>
< / div>
< / div>
EDIT:可能比我原来的答案更好的方法:
示例: http://jsfiddle.net/patrick_dw/xN6d5/5/
var $ target = $('#SearchHere')。children(),
$ next = $ target;
while($ next.length){
$ target = $ next;
$ next = $ next.children();
}
alert($ target.attr('id'));
或更短一些:
示例: http://jsfiddle.net/patrick_dw/xN6d5/ 6 /
var $ target = $('#SearchHere')。
while($ target.length){
$ target = $ target.children();
}
alert($ target.end()。attr('id')); //您需要.end()获取最后匹配的集合
原始答案:
这似乎有效:
示例: http://jsfiddle.net/xN6d5/4/
var levels = 0;
var deepest;
$('#SearchHere')。find('*')。each(function(){
if(!this.firstChild || this.firstChild.nodeType!== 1 ){
var levelsFromThis = $(this).parentsUntil('#SearchHere')。length;
if(levelsFromThis> levels){
levels = levelsFromThis;
deepest = this;
}
}
});
alert(deepest.id);
如果你知道最深的将是一个特定的标签通过用 .find('div')
替换 .find('*')
>
EDIT:更新为只检查当前元素的长度 有 firstChild
或如果是,firstChild不是类型1节点。
is there a cheep method to select the deepest child of an element ?
Example:
<div id="SearchHere">
<div>
<div>
<div></div>
</div>
</div>
<div></div>
<div>
<div>
<div>
<div id="selectThis"></div>
</div>
</div>
</div>
<div>
<div></div>
</div>
</div>
EDIT: This is likely a better approach than my original answer:
Example: http://jsfiddle.net/patrick_dw/xN6d5/5/
var $target = $('#SearchHere').children(),
$next = $target;
while( $next.length ) {
$target = $next;
$next = $next.children();
}
alert( $target.attr('id') );
or this which is even a little shorter:
Example: http://jsfiddle.net/patrick_dw/xN6d5/6/
var $target = $('#SearchHere').children();
while( $target.length ) {
$target = $target.children();
}
alert( $target.end().attr('id') ); // You need .end() to get to the last matched set
Original answer:
This would seem to work:
Example: http://jsfiddle.net/xN6d5/4/
var levels = 0;
var deepest;
$('#SearchHere').find('*').each(function() {
if( !this.firstChild || this.firstChild.nodeType !== 1 ) {
var levelsFromThis = $(this).parentsUntil('#SearchHere').length;
if(levelsFromThis > levels) {
levels = levelsFromThis;
deepest = this;
}
}
});
alert( deepest.id );
If you know that the deepest will be a certain tag (or something else), you could speed it up by replacing .find('*')
with .find('div')
for example.
EDIT: Updated to only check the length if the current element does not have a firstChild
or if it does, that the firstChild is not a type 1 node.
这篇关于在jQuery中选择最深的子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!