'use strict';
var toXPathStringLiteral = (function () {
function replacefn (match, p1) {
if (p1) {
return ',\u0027' + p1 + '\u0027';
}
return ',"' + match + '"';
}
return function toXPathStringLiteral (string) {
string = String(string);
if (/^"+$/g.test(string)) {
return '\u0027' + string + '\u0027';
}
switch (string.indexOf('"')) {
case -1:
return '"' + string + '"';
case 0:
return 'concat(' + string.replace(/("+)|[^"]+/g, replacefn).slice(1) + ')';
default:
return 'concat(' + string.replace(/("+)|[^"]+/g, replacefn) + ')';
}
};
}());
function handleClick (event) {
console.log(event.target.textContent);
}
function markupHighlight (targetString, contextNode) {
var doc = contextNode.nodeType === contextNode ? contextNode : contextNode.ownerDocument,
xpathResult = doc.evaluate('descendant::text()[contains(.,' + toXPathStringLiteral(targetString) + ')]', contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
df = doc.createDocumentFragment(),
mark = doc.createElement('mark');
mark.appendChild(doc.createTextNode(targetString));
for (var i = 0, xLen = xpathResult.snapshotLength, currentTextNode, stringList, textNode; i < xLen; ++i) {
currentTextNode = xpathResult.snapshotItem(i);
stringList = currentTextNode.data.split(targetString);
textNode = df.appendChild(doc.createTextNode(stringList[0]));
for (var j = 1, stringLen = stringList.length, textNode; j < stringLen; ++j) {
mark = mark.cloneNode(true);
df.appendChild(mark);
mark.addEventListener('click', handleClick, false);
textNode = textNode.cloneNode(false);
textNode.data = stringList[j];
df.appendChild(textNode);
}
currentTextNode.parentNode.replaceChild(df, currentTextNode);
}
}
markupHighlight('foo', document.body);
mark {
color: black;
background-color: #ddf;
border: solid 1px #55f;
}
<ul id="foo">
<li>foo1</li>
<li>foo2</li>
<li>foo3</li>
<li>
<ul>
<li>foo4-1</li>
<li>foo4-2 foo4-2</li>
<li>
<ul>
<li>foo4-3-1</li>
<li>foo4-3-2 foo4-3-2 foo4-3-2</li>
</ul>
</li>
</ul>
</li>
</ul>