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>>
Advertisement
Answer
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>