or can you provide me an example?
Well OK:
// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
var nonHtmlTags= {textarea:1, option:1, script:1, style:1, svg:1, math:1};
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1 && !(child.tagName in nonHtmlTags)) {
findText(child, pattern, callback);
} else if (child.nodeType==3) {
var matches= [];
var match;
while (match= pattern.exec(child.data))
matches.push(match);
for (var i= matches.length; i-->0;)
callback.call(window, child, matches[i]);
}
}
}
// Find text and wrap with span elements
//
function highlightText(element, pattern, className) {
findText(document.body, pattern, function(node, match) {
var span= document.createElement('span');
span.className= className;
node.splitText(match.index+match[0].length);
span.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(span, node.nextSibling);
});
}
highlightText(document.body, /[a-z]+/gi, 'english-word');
highlightText(document.body, /[\u0600-\u06FF]+/gi, 'persian-word');
Note the English and Persian regexps are very naïve and will fail for unusual characters, like Latin ï
or Arabic ﷽
. Coming up with a more complete expression is left as an exercise for the abecedarian.