-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.js
62 lines (51 loc) · 2.51 KB
/
jquery.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
58
59
60
61
62
/*
highlight v3 - Modified by Marshal (beatgates@gmail.com) to add regexp highlight, 2011-6-24
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>
*/
jQuery.fn.highlight = function(pattern) {
var regex = typeof(pattern) === "string" ? new RegExp(pattern, "i") : pattern; // assume very LOOSELY pattern is regexp if not string
nombreOccurence=0
function innerHighlight(node, pattern) {
var skip = 0;
if (node.nodeType === 3) { // 3 - Text node
var pos = node.data.search(regex);
if (pos >= 0 && node.data.length > 0) { // .* matching "" causes infinite loop
var match = node.data.match(regex); // get the match(es), but we would only handle the 1st one, hence /g is not recommended
var spanNode = document.createElement('span');
spanNode.className = 'highlight'; // set css
var middleBit = node.splitText(pos); // split to 2 nodes, node contains the pre-pos text, middleBit has the post-pos
var endBit = middleBit.splitText(match[0].length); // similarly split middleBit to 2 nodes
var middleClone = middleBit.cloneNode(true);
spanNode.appendChild(middleClone);
// parentNode ie. node, now has 3 nodes by 2 splitText()s, replace the middle with the highlighted spanNode:
middleBit.parentNode.replaceChild(spanNode, middleBit);
skip = 1; // skip this middleBit, but still need to check endBit
nombreOccurence+=1
}
} else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { // 1 - Element node
for (var i = 0; i < node.childNodes.length; i++) { // highlight all children
i += innerHighlight(node.childNodes[i], pattern); // skip highlighted ones
}
}
return skip;
}
/* return */ this.each(function() {
innerHighlight(this, pattern);
});
alert(nombreOccurence)
return nombreOccurence
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};