La risposta presentata da Andreas Josas è abbastanza buona. Tuttavia il codice aveva diversi bug quando il termine di ricerca appariva più volte nello stesso nodo di testo. Ecco la soluzione con questi bug corretti e inoltre l'inserto è fattorizzato in matchText per un uso e una comprensione più facili. Ora solo il nuovo tag viene costruito nel callback e restituito a matchText con un ritorno.
Aggiornato funzione matchtext con correzioni di bug:
var matchText = function(node, regex, callback, excludeElements) {
excludeElements || (excludeElements = ['script', 'style', 'iframe', 'canvas']);
var child = node.firstChild;
while (child) {
switch (child.nodeType) {
case 1:
if (excludeElements.indexOf(child.tagName.toLowerCase()) > -1)
break;
matchText(child, regex, callback, excludeElements);
break;
case 3:
var bk = 0;
child.data.replace(regex, function(all) {
var args = [].slice.call(arguments),
offset = args[args.length - 2],
newTextNode = child.splitText(offset+bk), tag;
bk -= child.data.length + all.length;
newTextNode.data = newTextNode.data.substr(all.length);
tag = callback.apply(window, [child].concat(args));
child.parentNode.insertBefore(tag, newTextNode);
child = newTextNode;
});
regex.lastIndex = 0;
break;
}
child = child.nextSibling;
}
return node;
};
Usage:
matchText(document.getElementsByTagName("article")[0], new RegExp("\\b" + searchTerm + "\\b", "g"), function(node, match, offset) {
var span = document.createElement("span");
span.className = "search-term";
span.textContent = match;
return span;
});
Se si desidera inserire ancoraggio (link) tag al posto del tag span, modificare l'elemento creare ad essere "un "invece di" span ", aggiungi una linea per aggiungere l'attributo href al tag e aggiungi" a "all'elenco excludeElements in modo che i link non vengano creati all'interno dei link.
fonte
2015-03-27 13:23:41
in questo caso si dovrà Repace il nodo di testo con i contenuti HTML –
@ArunPJohny Come posso fare? – alt
@ JacksonGariety: è necessario sostituire il nodo di testo con un nuovo elemento di span DOM e nodi di testo o modificare la proprietà innerHTML del genitore. Fai un tentativo, pubblica ciò che provi. – RobG