Searching of all nodes on page for particular piece of text


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*This useful extended function will allow you to
  2. pattern match a keyword across all the nodes in a
  3. page. See the example below for how GMail use something
  4. similar in concept for their search-keyword highlighting*/
  5.  
  6. $.fn.egrep = function(pat) {
  7. var out = [];
  8. var textNodes = function(n) {
  9. if (n.nodeType == Node.TEXT_NODE) {
  10. var t = typeof pat == 'string' ?
  11. n.nodeValue.indexOf(pat) != -1 :
  12. pat.test(n.nodeValue);
  13. if (t) {
  14. out.push(n.parentNode);
  15. }
  16. }
  17. else {
  18. $.each(n.childNodes, function(a, b) {
  19. textNodes(b);
  20. });
  21. }
  22. };
  23. this.each(function() {
  24. textNodes(this);
  25. });
  26. return out;
  27. };
  28.  
  29. // Here's an example of using this to highlight
  30. //all the nodes on the page that contain the keyword
  31. //'jQuery'
  32. $("#testbutton").click(function()
  33. {
  34. var n = $('body').egrep(/jquery/i);
  35. for (var i = 0; i < n.length; ++i)
  36. {
  37. void($(n[i]).css('background', 'yellow'));
  38. }
  39. });
  40.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.