This is not possible simply with CSS
. However, you can use a regex and the function replace
of Javascript
to show all the occurrences of a word in a text of a certain color.
What I do in this case is replace (detecting with a regex where the word hola
is) the original hola
for a new hola
that will be contained within a span
with a class azul
. This class is going to be the one that gives the style to the word.
Example:
var span = document.getElementById("texto");
var texto = span.innerHTML;
var textoReemplazado = texto.replace(/hola/g, "<span class=\"azul\">hola</span>");
span.innerHTML = textoReemplazado;
.azul{
color: blue;
}
<span id="texto">Texto hola este texto en el que pone hola, y a su vez otra vez hola, pero hola, y hola, y hola otra vez de nuevo.</span>
REMARK: This example would not work if you retrieved the HTML of a container (which will also retrieve the HTML of the child elements it contains) if any of the child elements have a id
or clase
the keyword that we want to replace, since it will also replace these ID or classes, which will cause inconsistencies in the HTML. You should use it with care.