Replace text with HTML when it contains value in the DIV

2

I have the div's:

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

I want the result 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>

I actually just want to replace the value of smiles **ex**: :D :( with an html with specific classes for each smile!

    
asked by anonymous 06.05.2015 / 06:03

1 answer

3

The best way is to iterate all the target elements and replace the smiles with the HTML element with the correct class. Apparently if you are going to 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've used arrays so that it's possible to add new smiles.

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>
    
06.05.2015 / 14:49