Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
How to convert all the elements of a for loop to a string

I have multiple letters, each written in their own span under an h1 tag, written in the HTML file. I then want to loop over these letters, and combine all the letters from the span elements into a single string that looks like this, "Hover over me!" (with the spaces). I have completed the for loop and extracted the inner HTML for each letter, but am having a hard time converting this to a single string, here is my HTML and JS code.

let text = document.querySelectorAll(".letter");
for (let i = 0; i < text.length; i++) {
  let array = [];
  let letters = text[i].innerHTML;
  console.log(letters);
}
<h1>
    <span class="letter">H</span>
    <span class="letter">o</span>
    <span class="letter">V</span>
    <span class="letter">E</span>
    <span class="letter">R</span>
    <span> </span>
    <span class="letter">O</span>
    <span class="letter">V</span>
    <span class="letter">E</span>
    <span class="letter">R</span>
    <span> </span>
    <span class="letter">M</span>
    <span class="letter">E</span>
    <span class="letter">!</span>
</h1>>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Get all the span elements, iterate over them taking their text content, and shove that into an array. If the letter is at first index of the str make it uppercase, otherwise lowercase. Then join up the string, and either log it to the console, or add it as the text content of another element as I've done here.

(I removed all the ids because an id needs to be unique, and they were mostly redundant here.)

const output = document.querySelector('.output');
const spans = document.querySelectorAll('span');

// The array is _outside_ of the loop
const arr = [];

for (let i = 0; i < spans.length; i++) {

  // Get a letter at the current index
  const letter = spans[i].textContent;

  // If it's zero uppercase the letter
  // otherwise lowercase it, and push it to
  // the array
  if (i === 0) {
    arr.push(letter.toUpperCase());
  } else {
    arr.push(letter.toLowerCase());  
  }
}

// `join` the array into a string, and
// either log it or add it as the text content
// of another element
output.textContent = arr.join('');
console.log(arr.join(''));
<h1>
  <span>H</span>
  <span>o</span>
  <span>V</span>
  <span>E</span>
  <span>R</span>
  <span> </span>
  <span>O</span>
  <span>V</span>
  <span>E</span>
  <span>R</span>
  <span> </span>
  <span>M</span>
  <span>E</span>
  <span>!</span>
</h1>
<div class="output"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming you have correctly populated the text array (and noting you could probably combine the extraction and string build in a single loop), the direct answer is:

var letters;
for (let i = 0; i < text.length; i++) {
    let letters += text[i].innerText;
}
console.log(letters);

Edited, based on comments & also probably we don't want to iteratively log the process of our loop, so moving the log out of the loop.

about 4 years ago · Juan Pablo Isaza Relatório

0

What about this solution:

// Select the characters by the tag...
const letters = document.getElementsByTagName('span');

// ... or by the class name
// const letters = document.getElementsByClassName('letter');

// Your final string
let str = '';

// Iterate over array of letters
for (let char of letters) {
  // Write each single character into variable 'str'
  str += char.textContent;
}

// Your result
console.log(str);
<!-- Don't apply same id to several elements, that's invalid HTML. Use classes instead -->
<h1>
  <span class="letter">H</span>
  <span class="letter">o</span>
  <span class="letter">V</span>
  <span class="letter">E</span>
  <span class="letter">R</span>
  <span> </span>
  <span class="letter">O</span>
  <span class="letter">V</span>
  <span class="letter">E</span>
  <span class="letter">R</span>
  <span> </span>
  <span class="letter">M</span>
  <span class="letter">E</span>
  <span class="letter">!</span>
</h1>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda