So I have something like this:
<div class="main">
<div class="useless">
text I don't want.
</div>
<div class="useless">
text I don't want.
</div>
<div class="narrow">
text I'm searching for
</div>
<div class="useless">
text I don't want.
</div>
<div class="useless">
text I don't want.
</div>
</div>
Using jQuery's lovely :contains
selector, I can search for a keyword, but it will return both the parent and the child.
I'd like it to only return elements who directly contain the word for which I'm searching.
Stackoverflow usefully suggested this link as a previous attempt, but it seems extremely clunky since it's crawling all dom nodes and requires a lot of unclear code.
This script will find all nodes that contain a specific text. It will also allow you to do any string tests on the text (regex etc).
function getNodesThatContain(text) {
var textNodes = $(document).find(":not(iframe, script, style)")
.contents().filter(
function() {
return this.nodeType == 3
&& this.textContent.indexOf(text) > -1;
});
return textNodes.parent();
};
console.log(getNodesThatContain("test"));
Here is a fiddle for testing: http://jsfiddle.net/85qEh/4/
PS - For increased speed use a different top level selector. For example if you only need inside #container then you would var textNodes = $('#container')...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With