Put plain text inside a label

1

I want to do something simple, give a rule of style to a part of a text

<span id="frase">la cancion me hace recordar una sensacion</span>
<script type="text/javascript">
   frase = document.querySelector("#frase").innerHTML
   frase.slice(-3) //ion

</script>

How can I apply a style rule to the output of my slice function?

The idea is to color it to show it of the word.

If styles can not be applied to normal text, then the possible solution would be to put the substring within a strong element

<span>sensac<strong>ion</strong></span>
    
asked by steven 25.04.2017 в 01:17
source

3 answers

3

The following example uses the span tag and the style attribute to format the extracted text with slice(-3) .

var frase = document.querySelector("#frase");
var fr = frase.innerHTML; //Variable auxiliar para abreviar un poco la siguiente línea
frase.innerHTML = fr.slice(0,fr.length -3) //Parte izquierda
  +'<span style="color:red">' //Abrir etiqueta para aplicar formato
  + fr.slice(-3)  //Texto a estilizar
  + '</span>';  //Cerrar etiqueta del formato aplicado
<span id="frase">la cancion me hace recordar una sensacion</span>
    
answered by 25.04.2017 в 03:34
2

A quick way is to replace, in the HTML content of the element, the matches with a label and a stylized class. For example:

const frase = document.getElementById('frase');
const fulltext = frase.textContent;
const html = frase.innerHTML;
const substr = fulltext.slice(-3);
const regexp = new RegExp(substr, 'g');

frase.innerHTML = html.replace(regexp, '<span class="highlight">' + substr + '</span>');
.highlight {
  background-color: greenyellow;
}
<span id="frase">la cancion me hace recordar una sensacion</span>

If the text is too large, you may lose some performance because every time you change the HTML of an element with this property, the DOM is rebuilt.

    
answered by 25.04.2017 в 03:15
0

I could solve it in the following way

  <script type="text/javascript">
    var elemento = document.querySelector("#frase");

    var frase = elemento.innerHTML;


    elemento.innerHTML = frase.slice(0,-3)+"<span style='background:yellow'>"+frase.slice(-3)+"</span>"
    
answered by 25.04.2017 в 22:07