Skip to content

Instantly share code, notes, and snippets.

@agibsonsw
Created January 8, 2016 22:11
Show Gist options
  • Save agibsonsw/a993c14ee172dfeb4d96 to your computer and use it in GitHub Desktop.
Save agibsonsw/a993c14ee172dfeb4d96 to your computer and use it in GitHub Desktop.
Bookmarklet to highlight selected word
javascript: (function() {
var els, i, txt = "";
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
} else {
txt = "";
}
if (txt) {
txt = txt.toString();
}
if (!txt || txt.length == 0) {
els = document.querySelectorAll(".hiColor");
i = els.length;
while (i--) {
els[i].style.backgroundColor = "";
els[i].className = "";
}
return null;
}
function searchNode(node, te, len) {
var pos, skip = 0,
spannode, middlebit, endbit, middleclone;
if (node.nodeType == 3) {
pos = node.data.toUpperCase().indexOf(te);
if (pos >= 0) {
spannode = document.createElement("SPAN");
spannode.className = "hiColor";
middlebit = node.splitText(pos);
endbit = middlebit.splitText(len);
middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
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 + searchNode(node.childNodes[child], te, len);
}
}
return skip;
}
searchNode(document.body, txt.toUpperCase(), txt.length);
els = document.querySelectorAll(".hiColor");
if (els && els.length) {
for (var i = 0; i < els.length; i++) {
els[i].style.backgroundColor = "yellow";
}
}
return null;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment