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

145
Vistas
How to add multiple array items as HTML content?

I need to extract some words from a string of text, insert every character of that words inside a span element and then replace the extracted words with the span elements. I have been able to convert characters into span elements but I can't figure out how to replace the extracted words with the span elements without deleting the other words.

<h1 class="title">Lorem ipsum dolor sit amet</h1>
const title = document.querySelector('.title');

// Extract required words and split them into single character
const firstWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('L')).toString().split('');
const secondWord = title.textContent.split(' ').filter(wrd => wrd.startsWith('a')).toString().split('');

// Return a new array with every character inside a span element
const spanCharacters = arr => {
    return arr.map(char => {
        const span = document.createElement('span');
        span.textContent = char;
        return span;
    });
};

const spanFirstWord = spanCharacters(firstWord);
// return [<span>L</span>, <span>o</span>, <span>r</span>, <span>e</span>, <span>m</span>]

const spanSecondWord = spanCharacters(secondWord);
// return [<span>a</span>, <span>m</span>, <span>e</span>, <span>t</span>]

Now, what I'd like to do is this:

<!-- before -->
<h1 class="title">Lorem ipsum dolor sit amet</h1>

<!-- after -->
<h1 class="title"><span>L</span><span>o</span><span>r</span><span>e</span><span>m</span> ipsum dolor sit <span>a</span><span>m</span><span>e</span><span>t</span></h1>

How could I replace the extracted words with the generated spans keeping the other words where they are?

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

0

Here is one way to do it:

const ttl=document.querySelector("h1.title"),
      txt=ttl.textContent;

function spanifyWords(beginsArr,txt){
 return txt.split(" ").map(w=>{
  if (beginsArr.some(b=>w.startsWith(b))) 
    w="<span>"+w.split("").join("</span><span>")+"</span>";
  return w
 }).join(" ");
}

ttl.innerHTML=spanifyWords(["a","L"],txt);
span {color: green; border:1px solid red}
<h1 class="title">Lorem ipsum dolor sit amet</h1>

Instead of . filter()-ing I use .map()to go through every word. Inside the callback function I check with .some() relative to some beginsArr whether the current word starts with one of the characters in question. If so, I "spanify" the word otherwise I return the word as is. At the end I stitch everything together again with .join().

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