css – Is it possible to style all occurrences of a word in a text?

Question:

I would like to know if it is possible to do this that I contemplate:

We have a text that and I want it to highlight X Word, for example, Every time I put "Hello" it appears written in Blue. Without having to label in each word, but to configure the styles.css so that when there is a "Hello" on the page it will put it directly in blue.

Answer:

Only with css it will not be possible, I leave you a code of this answer which works with javascript.

Then you can use css to look up the words and style it [word=hola] :

function makeHighlightable() {
  
  var n;
  var a=[];
  var walk = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);
  
  while (n = walk.nextNode()) a.push(n);
  
    for (var i = 0; i < a.length; i++) {
      
      var newSpan = document.createElement('span');      
      var words   = a[i].nodeValue.split(' ');
      
        for(var j = 0; j < words.length; j++) {
          
            var escapedWord = words[j].replace(/^\w /ig,'');
          
            words[j] = '<span word="'+escapedWord+'">'+words[j]+'</span>';
        }
      
        words = words.join(' ');
        
        newSpan.innerHTML = words;
        
        a[i].parentNode.replaceChild(newSpan,a[i]);
    }
}

makeHighlightable()
.hola1 [word=Hóla] { 
  color: blue;
  font-weight: bold;
}

.hola2 [word=hóla] { 
  color: darkorange ;
  font-weight: bold;
}

.hola3 [word=hola] { 
  color: red;
  font-weight: bold;
}
<p class="hola1">Hóla hóla ahora sin tilde Hola hola ahora con puntos Hóla::: hóla::: y sin puntos Hóla hóla</p>

<p class="hola2">Hóla hóla ahora sin tilde Hola hola ahora con puntos Hóla::: hóla::: y sin puntos Hóla hóla</p>

<p class="hola3">Hóla hóla ahora sin tilde Hola hola ahora con puntos Hóla::: hóla::: y sin puntos Hóla hóla</p>
Scroll to Top