jquery.highlight-3.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. highlight v3
  3. Highlights arbitrary terms.
  4. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
  5. MIT license.
  6. Johann Burkard
  7. <http://johannburkard.de>
  8. <mailto:jb@eaio.com>
  9. */
  10. /*
  11. * The Oxygen Webhelp plugin redistributes this file under the terms of the MIT license.
  12. * The full license terms of this license are available in the file MIT-License.txt
  13. * located in the same directory as the present file you are reading.
  14. */
  15. /*
  16. * List of modifications added by the Oxygen Webhelp plugin:
  17. * 1. Support to specify a custom class name for element that wraps highlighted terms
  18. */
  19. jQuery.fn.highlight = function(pat, className) {
  20. function innerHighlight(node, pat) {
  21. var skip = 0;
  22. if (node.nodeType === 3) {
  23. var pos = node.data.toUpperCase().indexOf(pat.toUpperCase());
  24. if (pos >= 0) {
  25. var spannode = document.createElement('span');
  26. spannode.className = className || 'highlight';
  27. var middlebit = node.splitText(pos);
  28. var endbit = middlebit.splitText(pat.length);
  29. var middleclone = middlebit.cloneNode(true);
  30. spannode.appendChild(middleclone);
  31. middlebit.parentNode.replaceChild(spannode, middlebit);
  32. skip = 1;
  33. }
  34. }
  35. else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
  36. for (var i = 0; i < node.childNodes.length; ++i) {
  37. i += innerHighlight(node.childNodes[i], pat);
  38. }
  39. }
  40. return skip;
  41. }
  42. return this.each(function() {
  43. innerHighlight(this, pat.toUpperCase());
  44. });
  45. };
  46. jQuery.fn.removeHighlight = function(className) {
  47. var className = className || 'highlight';
  48. function newNormalize(node) {
  49. for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
  50. var child = children[i];
  51. if (child.nodeType == 1) {
  52. newNormalize(child);
  53. continue;
  54. }
  55. if (child.nodeType != 3) { continue; }
  56. var next = child.nextSibling;
  57. if (next == null || next.nodeType != 3) { continue; }
  58. var combined_text = child.nodeValue + next.nodeValue;
  59. new_node = node.ownerDocument.createTextNode(combined_text);
  60. node.insertBefore(new_node, child);
  61. node.removeChild(child);
  62. node.removeChild(next);
  63. i--;
  64. nodeCount--;
  65. }
  66. }
  67. return this.find("span."+className).each(function() {
  68. var thisParent = this.parentNode;
  69. thisParent.replaceChild(this.firstChild, this);
  70. newNormalize(thisParent);
  71. }).end();
  72. };