-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathscripts.js
32 lines (26 loc) · 1023 Bytes
/
scripts.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
function search() {
var searchTerm = document.getElementById("search-input").value.trim();
var regex = new RegExp(searchTerm, "gi");
var textNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
var found = false;
while (textNodes.nextNode()) {
var node = textNodes.currentNode;
var parent = node.parentNode;
if (regex.test(node.nodeValue)) {
found = true;
var matches = node.nodeValue.match(regex);
var highlightedText = node.nodeValue.replace(regex, '<span class="highlight">$&</span>');
var tempDiv = document.createElement('div');
tempDiv.innerHTML = highlightedText;
var newNode = tempDiv.firstChild;
while (newNode) {
parent.insertBefore(newNode.cloneNode(true), node);
newNode = newNode.nextSibling;
}
parent.removeChild(node);
}
}
if (!found) {
alert("No such word found.");
}
}