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;
}
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()
<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>
$(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>