Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions jquery.highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand All @@ -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; };

Expand All @@ -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);
});
};