Return to Snippet

Revision: 28457
at July 8, 2010 17:29 by omerta83


Initial Code
/*This useful extended function will allow you to 
pattern match a keyword across all the nodes in a 
page. See the example below for how GMail use something 
similar in concept for their search-keyword highlighting*/  
  
$.fn.egrep = function(pat) {  
 var out = [];  
 var textNodes = function(n) {  
  if (n.nodeType == Node.TEXT_NODE) {  
   var t = typeof pat == 'string' ?  
    n.nodeValue.indexOf(pat) != -1 :  
    pat.test(n.nodeValue);  
   if (t) {  
    out.push(n.parentNode);  
   }  
  }  
  else {  
   $.each(n.childNodes, function(a, b) {  
    textNodes(b);  
   });  
  }  
 };  
 this.each(function() {  
  textNodes(this);  
 });  
 return out;  
};  
  
// Here's an example of using this to highlight  
//all the nodes on the page that contain the keyword  
//'jQuery'  
$("#testbutton").click(function()  
{  
var n = $('body').egrep(/jquery/i); 
for (var i = 0; i < n.length; ++i) 
{ 
   void($(n[i]).css('background', 'yellow'));  
 }  
});

Initial URL


Initial Description


Initial Title
Searching of all nodes on page for particular piece of text

Initial Tags
javascript, jquery

Initial Language
JavaScript