Pour effectuer une recherche et un remplacement sur du texte, vous devez vérifier chaque nœud de texte séparément et effectuer les opérations DOM splitText
afin de le démonter lorsqu'une correspondance est trouvée. Par exemple:
function findText(element, pattern, callback) {
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1) {
var tag= child.tagName.toLowerCase();
if (tag!=='script' && tag!=='style' && tag!=='textarea')
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]);
}
}
}
findText(element, /\bWorld\b/g, function(node, match) {
var span= document.createElement('span');
node.splitText(match.index+match[0].length);
span.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(span, node.nextSibling);
});
Nope. Les parties de nœuds de texte ne sont pas des éléments DOM valides. –
Vérifiez le plugin [jQuery "highlight"] (http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html) – Pointy