Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - How do I select the innermost element?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...