Skip to content

Instantly share code, notes, and snippets.

@martianyi
Created April 21, 2018 08:27
Show Gist options
  • Save martianyi/aa7a4007f466a9f16e6fdfa85094510b to your computer and use it in GitHub Desktop.
Save martianyi/aa7a4007f466a9f16e6fdfa85094510b to your computer and use it in GitHub Desktop.
bookmarklet to search text in page
javascript: (function() {
var count = 0,
text;
text = prompt("Search phrase:", "");
if (text == null || text.length == 0) return;
if (!window.__obody) window.__obody = document.body.cloneNode(true);
function searchWithinNode(node, te, len) {
var pos, skip, spannode, middlebit, endbit, middleclone;
skip = 0;
if (node.nodeType == 3) {
pos = node.data.toUpperCase().indexOf(te);
if (pos >= 0) {
spannode = document.createElement("SPAN");
spannode.style.backgroundColor = "yellow";
middlebit = node.splitText(pos);
endbit = middlebit.splitText(len);
middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
++count;
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && node.tagName.toUpperCase() != "SCRIPT" && node.tagName.toUpperCase != "STYLE") {
for (var child = 0; child < node.childNodes.length; ++child) {
child = child + searchWithinNode(node.childNodes[child], te, len);
}
}
return skip;
}
document.body = window.__obody.cloneNode(true);
searchWithinNode(document.body, text.toUpperCase(), text.length);
alert("Found " + count + " occurrence" + (count == 1 ? "" : "s") + " of '" + text + "'.");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment