Select only those items that contain text.
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 the jQuery lovely :contains selector , I can search for a keyword, but it will return both parent and child.
I would like it to return elements that directly contain the word for which I am looking.
Stackoverflow has helpfully suggested this link as a previous attempt, but it seems extremely awkward as it scans all dom nodes and requires a lot of fuzzy code.
This script will find all nodes that contain specific text. It will also allow you to perform any string tests in the text (regular expression, 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 the fiddle for testing: http://jsfiddle.net/85qEh/4/
PS - Use a different high-level selector to increase speed. For example, if you only need the container #container, you would var textNodes = $('#container')...
The solution, which is provided in another question, as indicated above, but, apparently, is not a very appreciated solution:
$("div:contains('searching')").filter(function() { return ( $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .filter(":contains('searching')").length > 0) }).css('border', 'solid 1px black'); I would add it less clunky than writing a huge thing to scan all the DOM nodes and actually have to affect fewer places when they are narrowly limited.
If anyone has any better ideas, I am definitely interested.
Try it in JS
$('div >:contains("text Im searching for")')