From 0690468bfd5a819712cf48093e916682ea793003 Mon Sep 17 00:00:00 2001 From: David Paz Date: Wed, 1 Jun 2016 13:33:28 +0200 Subject: [PATCH] Allow ignore html elements selectively Ad one more condition check in order to allow to configure the thml elements to ignore. Add one more option to settings: ignoreNode, an array of elements. --- jquery.highlight.js | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/jquery.highlight.js b/jquery.highlight.js index 9dcf3c7..2436b70 100644 --- a/jquery.highlight.js +++ b/jquery.highlight.js @@ -44,7 +44,7 @@ */ jQuery.extend({ - highlight: function (node, re, nodeName, className) { + highlight: function (node, re, nodeName, className, ignore) { if (node.nodeType === 3) { var match = node.data.match(re); if (match) { @@ -57,11 +57,15 @@ jQuery.extend({ wordNode.parentNode.replaceChild(highlight, wordNode); return 1; //skip added node in parent } - } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children - !/(script|style)/i.test(node.tagName) && // ignore script and style nodes - !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted - for (var i = 0; i < node.childNodes.length; i++) { - i += jQuery.highlight(node.childNodes[i], re, nodeName, className); + } else if (node.nodeType === 1 && node.childNodes) { // only element nodes that have children + var regex = new RegExp("(" + ignore.join("|") + ")", "i"), + condition = !regex.test(node.tagName) && // ignore configured nodes + !(node.tagName === nodeName.toUpperCase() && node.className === className); // skip if already highlighted + + if(condition) { + for (var i = 0; i < node.childNodes.length; i++) { + i += jQuery.highlight(node.childNodes[i], re, nodeName, className, ignore); + } } } return 0; @@ -80,17 +84,23 @@ jQuery.fn.unhighlight = function (options) { }; jQuery.fn.highlight = function (words, options) { - var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; + var settings = { + className: 'highlight', + element: 'span', + caseSensitive: false, + wordsOnly: false, + ignoreNode: ['script', 'style'] + }; jQuery.extend(settings, options); - + if (words.constructor === String) { words = [words]; } words = jQuery.grep(words, function(word, i){ - return word != ''; + return word != ''; }); words = jQuery.map(words, function(word, i) { - return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }); if (words.length == 0) { return this; }; @@ -100,9 +110,9 @@ jQuery.fn.highlight = function (words, options) { pattern = "\\b" + pattern + "\\b"; } var re = new RegExp(pattern, flag); - + return this.each(function () { - jQuery.highlight(this, re, settings.element, settings.className); + jQuery.highlight(this, re, settings.element, settings.className, settings.ignoreNode); }); };