我如何选择最内层的元素? [英] How do I select the innermost element?

查看:150
本文介绍了我如何选择最内层的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,我将如何尽可能下降到HTML树中?



为简单起见,我只有一条路径向下。



(相关但奖金:我如何找到具有多条向下路径的最深元素?)

 < HTML> 
< table id =table0>
< tr>
< td id =cell0>
< div classsimple>我想更改此信息< / div>
< / td>
< / tr>
< / table>
< / html>

我想更改名为 cell0 的单元格的最内层HTML,但我不一定知道里面所有类的名字。是否有可能在不知道这些名称的情况下选择此项目?



非常感谢!

解决方案

  $('body *:不是(:有( *))'); 

或者,在您的具体情况 $('#cell0 *:not (:has(*))');



对于多个路径 - 如果有多个同样嵌套的节点呢?这个解决方案会给你一个祖先数量最多的节点的数组。 (:has(*))'),maxDepth = 0,deepest = [];
all.each(function(){
var depth = $(this).parents()。length || 0;
if(depth> maxDepth){
deepest = [this];
maxDepth = depth;
}
else if(depth == maxDepth){
deepest.push(this);
}
});

同样,在您的情况下,您可能想要查看表格单元格的最深处的元素,返回一行:

  $('#table0 td *:not(:has(*))'' ); 

- 这将返回一个jQuery对象,其中包含表格中每个单元格的所有最内层子节点。 / p>

In jQuery, how would I descend as far as possible into the HTML tree?

For simplicity, I only have one path going downward.

(related but bonus: how do I find the deepest element with multiple downward paths?)

<html>  
  <table id="table0">  
    <tr>  
      <td id="cell0">  
        <div class"simple">  I want to change this information </div>  
      </td>
    </tr>  
  </table>  
</html>

I want to change the innermost HTML of the cell named cell0 but I don't necessarily know the names of all the classes inside. Is it possible to select this far without knowing these names?

Thanks much!

解决方案

For single path just find the element that doesn't have child nodes:

$('body *:not(:has("*"))');

Or, in your more specific case $('#cell0 *:not(:has("*"))');

For multiple paths - what if there are multiple equally nested nodes? This solution will give you an array of all nodes with highest number of ancestors.

var all = $('body *:not(:has("*"))'), maxDepth=0, deepest = []; 
all.each( function(){ 
    var depth = $(this).parents().length||0; 
    if(depth>maxDepth){ 
        deepest = [this]; 
        maxDepth = depth; 
    }
    else if(depth==maxDepth){
        deepest.push(this); 
    }
});

Again, in your situation you probably want to get to table cells' deepest elements, so you're back to a one-liner:

$('#table0 td *:not(:has("*"))');

- this will return a jQuery object containing all the innermost child nodes of every cell in your table.

这篇关于我如何选择最内层的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆