I am trying to edit the jQuery hightlight plug in to highlight multiple words. It works great until you hit the space bar, then it causes FF to freeze in an infinite loop.
FireBug reports that .toUpperCase is not a function, but when I change the same code back, so it is not altering an array element, it’s fine, but does not highlight the two words, only the first one. When the space bar is hit all highlighting goes away.
Here is the what I have so far. The code in question is in the return this.each(function(){}) block at the end:
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
var parts = pat.split(' ');
console.log(parts);
for (var i in parts) {
innerHighlight(this, parts[i].toUpperCase());
console.log("parts["+i+"] >> " + parts[i]);
}
});
};
Here is the console output in FireBug:
["guy"] jquery...ht-3.js (line 46)
parts[0] >> guy jquery...ht-3.js (line 49)
parts[i].toUpperCase is not a function
[Break On This Error] innerHighlight(this, parts[i].toUpperCase());
jquery...ht-3.js (line 48)
any help would be greatly appreciated!
Oh dear. That plugin is using an unfiltered
for...inloop to iterate over an array. That’s bad:So, change this:
to this: