Highlight
highlight text basic 1st version
by slawe
HTML
<button onclick="TestTextHighlighting('is')">Highlight</button>
<div id="testDocument">
This is a test
<span> This is another test</span>
Some text message
<span>Test123</span>
</div>
CSS
.highlight
{
background: #D3E18A;
}
.light
{
background-color: yellow;
}
JavaScript
function TestTextHighlighting(highlightText) {
var container = document.getElementById("testDocument");
InstantSearch.highlight(container, highlightText);
}
var InstantSearch = {
"highlight": function (container, highlightText) {
var internalHighlighter = function (options) {
var id = {
container: "container",
tokens: "tokens",
all: "all",
token: "token",
className: "className",
sensitiveSearch: "sensitiveSearch"
},
tokens = options[id.tokens],
allClassName = options[id.all][id.className],
allSensitiveSearch = options[id.all][id.sensitiveSearch];
function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll) {
var nodeVal = node.nodeValue, parentNode = node.parentNode,
i, j, curToken, myToken, myClassName, mySensitiveSearch,
finalClassName, finalSensitiveSearch, foundIndex, begin,
matched, end, textNode, span, isFirst;
for (i = 0, j = tokenArr.length; i < j; i++) {
curToken = tokenArr[i];
myToken = curToken[id.token];
myClassName = curToken[id.className];
mySensitiveSearch = curToken[id.sensitiveSearch];
finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);
finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);
isFirst = true;
while (true) {
if (finalSensitiveSearch)
foundIndex = nodeVal.indexOf(myToken);
else
foundIndex = nodeVal;
if (foundIndex < 0) {
if (isFirst)
break;
if (nodeVal) {
textNode = document.createTextNode(nodeVal);
parentNode.insertBefore(textNode, node);
} // End if (nodeVal)
parentNode.removeChild(node);
...