有人能告诉我是否可以根据元素的内容而不是根据ID或类来查找元素吗?
我试图查找没有独特类或ID的元素。(然后我需要找到该元素的父元素。)
.filter
д»ЈжӣҝгҖӮ $('div').filter(function(){ return $(this).text().toLowerCase() === 'test';})
зҡ„ж„ҸжҖқжҳҜйҖүеҸ–жүҖжңүdivе…ғзҙ дёӯж–Үжң¬еҶ…е®№дёәвҖңtestвҖқзҡ„е…ғзҙ гҖӮ - gen_Eric$('div:contains( "test" )').css('background-color', 'red');
- M Katz在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;
}
<li>Hello <a href='#'>World</a>, How Are You.
。如果搜索的是“ How”,则条件将失败。 - me_digvijay伙计们,我知道这已经是老问题了,但是我有一个解决方案,我认为比所有其他解决方案都要好。首先,它克服了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()
希望将来有人发现它有用。
Rocket的答案不起作用。
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
我只是修改了他这里的演示,你可以看到选择了根DOM。
$('div:contains("test"):last').css('background-color', 'red');
在代码中添加":last"选择器以解决此问题。
$('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>
我认为这是最好的方法。
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
是的,使用jQuery中的contains
选择器。
$(function() {
const ELEMTYPE = Node.ELEMENT_NODE
const TEXTTYPE = Node.TEXT_NODE
/*
Behaves a bit like Python's os.walk().
The `topdown` parameter is not strictly necessary for this example.
*/
function* walk_text(root, topdown=true) {
const childs = []
const textchilds = []
for (const child of root.childNodes) {
const childtype = child.nodeType
if (childtype === ELEMTYPE) {
childs.push(child)
} else if (childtype === TEXTTYPE) {
textchilds.push(child)
}
}
if (topdown) {
yield [root, textchilds]
}
for (const child of childs) {
yield* walk_text(child, topdown)
}
if (!topdown) {
yield [root, textchilds]
}
}
function* walk_matching(startnode, nodepat, textpat) {
for ( [elem, textchilds] of walk_text(startnode) ) {
if ( nodepat.test(elem.nodeName) ) {
for ( const textchild of textchilds ) {
if ( textpat.test(textchild.nodeValue) ) {
yield elem
break
}
}
}
}
}
// raw dom node
let startnode = $('body')[0]
// search for element nodes with names matching this pattern ...
let nodepat = /^div$/i
// ... containing direct child text nodes matching this pattern
let textpat = /\bhobbit\b/i
for ( const node of walk_matching( startnode, nodepat, textpat ) ) {
$(node).css({
border: '1px solid black',
color: 'black'
})
}
});
div {
margin:10px 0;
padding: 10px;
border: 1px solid silver;
color: silver;
font-style:italic;
}
div:before {
display:block;
content: attr(name);
font-style:normal;
}
/* Inserted by SO, we are not interested in it */
body + div {
display: none;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Find the hobbits</title>
</head>
<body>
<div name='Tolkien'>
book writer
<div name='Elrond'>
elven king
<div name='Arwen'>elven princess</div>
<div name='Aragorn'>human king, son-in-law</div>
</div>
<div name='Gandalf'>
wizard, expert for hobbits
<div name='Bilbo'>
old hobbit
<div name='Frodo'>
young hobbit
<div name='Samweis'>best friend hobbit</div>
</div>
</div>
<div name='Gollum'>ex hobbit</div>
<div name='Odo'>hobbit</div>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
其他答案(搜索“霍比特”时)如下:
所有这些答案都有道理,具体取决于您想要做什么。选择明智,因为Rocket Hazmat的答案、Morgs的答案和Terry Lin的答案比我的解决方案快两倍以上。我猜这是因为它们不需要遍历整个DOM。大多数使用.filter()
的答案执行非常快。