var elements = document.getElementsByTagName('*'); for (var i = 0; i < elements.length; i++) { var element = elements[i]; for (var j = 0; j < element.childNodes.length; j++) { var node = element.childNodes[j]; if (node.nodeType === 3) { var text = node.nodeValue; var replacedText = text.replace(/[word or phrase to replace here]/gi, '[new word or phrase]'); if (replacedText !== text) { element.replaceChild(document.createTextNode(replacedText),node); } } } } 

This script should make words and replace them with others (this script is for expansion). Please help to remake it so that it changes the color of the replaced words, say red.

  • And what signs have green words? The script you show is looking for a string. - Kirill Korushkin
  • He looks for the word, then he will be replaced by another, but how can we make the replaced word be red ? Surik Pozoyan
  • How do we know that the word is green? \ Does he have a class or can an inline style? - Kirill Korushkin
  • var replacedText = text.replace (/ [word or phrase to replace here] / gi, '<span style = "color: green"> [new word or phrase] </ span>'); - axmed2004
  • It does not work to display all the text, he adds it as text instead of adding as code - Surik Pozoyan

1 answer 1

The fact is that you create a text element, and you need to create an element based on the markup.

Creating a new DOM element from an HTML string using DOM methods or Prototype

 var elements = document.getElementsByTagName('*'); for (var i = 0; i < elements.length; i++) { var element = elements[i]; for (var j = 0; j < element.childNodes.length; j++) { var node = element.childNodes[j]; if (node.nodeType === 3) { var text = node.nodeValue; var replacedText = text.replace(/яблок/gi,'<span class="red">pineapple</span>'); if (replacedText !== text) { var div = document.createElement('div'); div.innerHTML = replacedText.trim(); element.replaceChild(div.firstChild, node); } } } } 
  • thank you so much <3 <3 <3 mykola - Surik Pozoyan