【问题标题】:Find element whose immediate descendant contains text查找其直接后代包含文本的元素
【发布时间】:2016-09-29 04:08:36
【问题描述】:
我有:
<div id="new">
"hello new"
<div id="some">
"hello some new man"
</div>
</div>
我想选择其直接后代具有文本“hello some”的 div。我试过了:
$('div:contains("hello some")')
这显示了 id 为新的和一些的 div
我有许多具有不同 id 的 div,但包含文本“hello some”。我想选择所有这样的 div 的
【问题讨论】:
标签:
jquery
jquery-selectors
【解决方案1】:
您可以为此目的使用XPath,它是text() 函数。
function getElementByXpath (path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
// get any element containing this text
getElementByXpath('//*[contains(text(), "hello some")]')
hello some