本文翻译自:jQuery: find element by text
Can anyone tell me if it’s possible to find an element based on its content rather than by an id or class ? 谁能告诉我是否有可能根据其内容而不是ID或类来查找元素?
I am attempting to find elements that don’t have distinct classes or id’s. 我正在尝试查找没有不同类或ID的元素。 (Then I then need to find that element’s parent.) (然后,我需要找到该元素的父对象。)
#1楼
参考:https://stackoom.com/question/uIL6/jQuery-按文本查找元素
#2楼
In jQuery documentation it says: 在jQuery文档中说:
The matching text can appear directly within the selected element, in any of that element’s descendants, or a combination 匹配的文本可以直接出现在所选元素中,该元素的任何后代中或组合中
Therefore it is not enough that you use :contains()
selector , you also need to check if the text you search for is the direct content of the element you are targeting for, something like that: 因此,仅使用:contains()
选择器还不够,还需要检查搜索的文本是否是您要定位的元素的直接内容 ,例如:
function findElementByText(text) {
var jSpot = $("b:contains(" + text + ")")
.filter(function() { return $(this).children().length === 0;})
.parent(); // because you asked the parent of that element
return jSpot;
}
#3楼
Rocket’s answer doesn’t work. 火箭的答案不起作用。
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
I simply modified his DEMO here and you can see the root DOM is selected. 我只是在这里修改了他的DEMO ,您可以看到已选择根DOM。
$('div:contains("test"):last').css('background-color', 'red');
add ” :last ” selector in the code to fix this. 在代码中添加“ :last ”选择器以解决此问题。
#4楼
Best way in my opinion. 我认为最好的方法。
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
#5楼
Fellas, I know this is old but hey I’ve this solution which I think works better than all. Fellas,我知道这很老了,但是我有这个解决方案,我认为它比所有方法都有效。 First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with: 首要的是克服了jquery:contains()附带的区分大小写的问题:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful. 希望不久的将来有人对您有所帮助。
#6楼
The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree. 以下jQuery选择包含文本但没有子级的div节点,它们是DOM树的叶节点。
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
<div>div1 <div>This is a test, nested in div1</div> <div>Nested in div1<div> </div> <div>div2 test <div>This is another test, nested in div2</div> <div>Nested in div2</div> </div> <div> div3 </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>