Replace text with HTML when it contains value in DIV

Asked

Viewed 661 times

2

I got the divs:

<div class="mensagem">
   <div class="texto-mensagem">:D, :( Olá Mundo!</div>
</div>

I want the results to print this:

<div class="mensagem">
   <div class="texto-mensagem">
      <div class="smile-happy>":D</div>, 
      <div class="smile-sad">:(</div>  
      Olá Mundo!
   </div>
</div>

Actually I just want to replace the value of the Smiles **ex**: :D :( by an html with specific classes for each Smile!

1 answer

3


The best way is to iterate all target elements and replace Smiles with the HTML element with the correct class. Apparently if you will use this code to format the text, then to keep your code more semantic, I suggest using the element <span> instead of <div>

It is possible to do with pure javascript, without jQuery.

I used arrays so that it is possible to include new ones.

var textos = document.querySelectorAll('.texto-mensagem');
var smiles = [':D', ':('];
var classes = ['happy', 'sad'];
for (var i = 0; i < textos.length; i++) {
  for (var j = 0; j < smiles.length; j++) {
    var div = '<span class="smile-' + classes[j] + '">' + smiles[j] + '</span>';
    textos[i].innerHTML = textos[i].innerHTML.split(smiles[j]).join(div);
    // poderia ser feito com a função replace() mas substitui apenas a primeira ocorrência
  }
}
.smile-happy {background: #0F0;}
.smile-sad {background: #99F;}
<div class="mensagem">
    <div class="texto-mensagem">:D, :( Olá Mundo!</div>
    <div class="texto-mensagem">sad smile :(</div>
    <div class="texto-mensagem">vários iguais :D :D :D</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.