Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
How to inject html tags within a script in Javascript?

I have a string where I would like to inject a <br> tag based on array values.

My html code:

'Hello people. `<span>`Hello to everyone`</span>`'; 
<script>
    let array = ['Hello', 'to everyone'];
</script>

I need to inject <br> tag between 'Hello' and 'to everyone' inside <span> based on contents of array. How can I do it without replacing the tags and not affecting the first 'Hello' word?

Expected output:

'Hello people. `<span>`Hello `<br>` to everyone`</span>`'

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You should do this by clearing the contents of the <span> element, then iterate over the array with a foreach method where you add the contents of the array then a line break(<br>).You can define the line break with const lineBreak = document.createElement('br'); , then you can add it to the span element with some DOM manipulation like this elem.appendChild(lineBreak)

Here is the full code:

<head>
  <title>hello world</title>

</head>
<body>
  <p>Hello people. <span id='message'  style="WHITE-SPACE: br">Hello to everyone</span></p>
  <script>
    function split_words(){
      let array = ['Hello', 'to everyone'];
      const elem = document.getElementById('message');
      let result = '';
      const lineBreak = document.createElement('br');
      elem.innerHTML = '';
      array.forEach(word => {
        elem.innerHTML += word;
        elem.appendChild(lineBreak)
        
      });
    }
    window.onload = split_words(); 
  </script>
</body>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could just use \n or <br/> within the text. Your code will look something like so

document.write(`Hello people. <span>Hello <br> to everyone</span>`); 
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda