Last active
January 28, 2016 22:17
-
-
Save jphase/8288780 to your computer and use it in GitHub Desktop.
jQuery regex search element text/contents and return matches based on child element containing regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Escape all RegEx reserved characters from string | |
function escRegExp(str) { | |
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); | |
} | |
// Return matched elements based on regex contents | |
function highlight(regex, element, child) { | |
// Create a regex based on the match string | |
var regex = new RegExp(escRegExp(regex), 'gim'); | |
// Generate results based on regex matches within match_parent | |
var results = []; | |
// Check for element | |
if($(element).length) { | |
// Match regex on parent element | |
var match = $(element).text().match(regex); | |
if(match != null) { | |
// Push our matches onto results | |
$(element).find(child).each(function(index, value) { | |
// Push child onto to results array if it contains our regex | |
if($(this).text().match(regex)) results.push($(this)); | |
}); | |
} | |
} | |
return results; | |
} | |
// Get results example usage | |
var results = highlight('has', '#anothercontainer', 'div, li'); | |
// Make them sexy and pink | |
$.each(results, function() { | |
$(this).css({color: 'pink'}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="anothercontainer"> | |
<div>not me</div> | |
<div>has one here</div> | |
<div>but not here</div> | |
<ul> | |
<li>this has "has" in it</li> | |
<li>this doesn't</li> | |
<li>has this one?</li> | |
<li>not this one</li> | |
</ul> | |
</div> | |
<hr>Stuff below here is ignore because it's not in #anothercontainer<hr> | |
<div id="container"> | |
<div>even though there's a has, it will only work with #anothercontainer</div> | |
<ul> | |
<li>has</li> | |
<li>don't have</li> | |
</ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an easy function to return jQuery elements based on their contents matching a string (recursively) based on the parent or specific containing elements.
http://jsfiddle.net/jphase/VqvLV/2/
This code was a port of the main chunk of logic used in my node bot that scrapes content from other websites. It is now repurposed for folks that need a straight jQuery solution.