sis*_*sko 285 jquery text find
任何人都可以告诉我,是否可以根据其内容而不是ID或类找到元素?
我试图找到没有不同类或id的元素.(然后我需要找到该元素的父级.)
Roc*_*mat 404
您可以使用:contains选择器根据其内容获取元素.
$('div:contains("test")').css('background-color', 'red');Run Code Online (Sandbox Code Playgroud)
yoa*_*nea 88
在jQuery文档中,它说:
匹配的文本可以直接出现在所选元素中,任何元素的后代或组合中
因此,使用: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;
}
Run Code Online (Sandbox Code Playgroud)
Mor*_*rgs 20
费拉斯,我知道这已经老了,但是嘿,我有这个解决方案,我觉得比所有人都好.首先,克服了jquery:contains()随附的Case Sensitivity:
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()
Run Code Online (Sandbox Code Playgroud)
希望有人在不久的将来发现它有用.
Ter*_*Lin 16
火箭的答案不起作用.
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我只是在这里修改了他的DEMO,你可以看到根DOM被选中了.
$('div:contains("test"):last').css('background-color', 'red');
Run Code Online (Sandbox Code Playgroud)
在代码中添加" :last "选择器来解决此问题.
rpl*_*ndo 14
在我看来最好的方式.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
Run Code Online (Sandbox Code Playgroud)
Nic*_*kin 11
下面的 jQuery 选择包含文本但没有子节点的 div 节点,它们是 DOM 树的叶节点。
$('div:contains("test"):not(:has(*))').css('background-color', 'red');Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)