-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.highlight-3.js
57 lines (49 loc) · 1.58 KB
/
jquery.highlight-3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
highlight v3
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:[email protected]>
*/
jQuery.fn.highlight = function(pat, fbgcolor) {
function innerHighlight(node, pat, fbgcolor) {
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';
// Setting padding & margin to 0px to fix this -- https://github.com/curiosity/Find-Many-Strings/issues/1
fbgcolor += ";padding: 0px; margin: 0px;";
spannode.setAttribute('style', fbgcolor);
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, fbgcolor);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase(), fbgcolor);
});
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
var txtNode = document.createTextNode(this.textContent);
with (this.parentNode) {
replaceChild(txtNode, this);
normalize();
}
}).end();
};