使用jQuery选择器遍历树中的最后一个子元素 [英] Traversing to the last child element in a tree using jQuery selector
本文介绍了使用jQuery选择器遍历树中的最后一个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<div id="myDIV">
<div>
<span>
<a href="#">Seek me!</a>
</span>
</div>
</div>
如何使用jQuery选择器找到 A 标签(不遍历children()) 如果我只知道myDIV ID.
How can I find A tag using jQuery selector (not looping through children()) If I know only myDIV id.
嗯,听起来确实有点尴尬.例如,我单击了#myDIV,我需要从最后一个子标记中获取文本.它可以是A,span,div,p等.而且myDIV甚至不能包含任何子元素.
Well, it really sounds a bit awkward. For example I've clicked #myDIV and i need to get text from the last child tag. It could A, span, div, p, whatever. Also myDIV could not even have any children elements.
请问我的英语
推荐答案
像这样:
$("#myDIV :not(:has(*))")
这将找到所有最后的叶子"元素,如果需要,您可以限制为仅<a>
,依此类推.对于您的标记:
This will find all the last "leaf" elements, you could restrict to only <a>
, etc if you wanted. For your markup:
$("#myDIV :not(:has(*))").text() // "Seek me!"
$("#myDIV :not(:has(*))").length // 1
:empty
在这里不起作用(因为它有一个文本节点子节点),但找到没有子元素的东西,此处是显示此内容的示例页面.
这篇关于使用jQuery选择器遍历树中的最后一个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文