With xiaoyi, I found several solutions:
- Stop the loop and replace only the first match
- Globalization of functions for searching / replacing multiple keywords
I think it can be optimized, but for me it works like a charm, and I share it if it can help anyone (do not forget to change the purpose of the document, here is the “parent”)
(function(){ // don't replace text within these tags var skipTags = { 'a': 1, 'style': 1, 'script': 1, 'iframe': 1, 'meta':1, 'title':1, 'img':1, 'h':1 }; // find text nodes to apply replFn to function findKW( el, term, replFn ) { var child, tag,found=false; for (var i = 0;i<=el.childNodes.length - 1 && !found; i++) { child = el.childNodes[i]; if (child.nodeType == 1) { // ELEMENT_NODE tag = child.nodeName.toLowerCase(); if (!(tag in skipTags)) { findKW(child, term, replFn); } } else if (child.nodeType == 3) { // TEXT_NODE found=replaceKW(child, term, replFn); // if found=true, we stop the loop } } }; // replace terms in text according to replFn function replaceKW( text, term, replFn) { var match, matches = [],found=false; while (match = term.exec(text.data)) { matches.push(match); } for (var i = 0;i<=matches.length - 1 && !found; i++) { match = matches[i]; // cut out the text node to replace text.splitText(match.index); text.nextSibling.splitText(match[1].length); text.parentNode.replaceChild(replFn(match[1]), text.nextSibling); if(matches[i])found=true;// To stop the loop } return found; }; // First search/replace var replTerm = 'keyword'; findKW( parent.document.body, new RegExp('\\b(' + replTerm + ')\\b', 'gi'), function (match) { var link = parent.document.createElement('a'); link.href = 'http://www.okisurf.com/#q=' + replTerm; link.target = '_blank'; link.innerHTML = match; return link; } ); // A second search/replace var replTerm = 'word'; findKW( parent.document.body, new RegExp('\\b(' + replTerm + ')\\b', 'gi'), function (match) { var link = parent.document.createElement('a'); link.href = 'http://www.okisurf.com/
I also found that the second solution does not work with Internet Explorer, because it does not accept the createTreeWalker() DOM function
Valky
source share