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

160
Visualizações
trying to add two querySelectorAll items to a forEach loop in JavaScript

I've been trying to apply the newText.innerText to the oldText.innerText and it only takes the last element in the newText and applies it to all the oldText I've tried to add the index and the array to the loop and run the code after adding them as a number counter but it still wouldn't work, I've also tried to define a new element and assign the newText value to it but still it didn't work

      <body>
        <h3 class="oldText">oldText</h3>
        <h3 class="oldText">oldText</h3>
        <h3 class="oldText">oldText</h3>
        <h3 class="oldText">oldText</h3>
        <h3 class="oldText">oldText</h3>
    
        <h3 class="newText">newText1</h3>
        <h3 class="newText">newText2</h3>
        <h3 class="newText">newText3</h3>
        <h3 class="newText">newText4</h3>
        <h3 class="newText">newText5</h3>
        
<script> 

    var oldText = document.querySelectorAll('.oldText')
    var newText = document.querySelectorAll('.newText')
    oldText.forEach((oldT) => {
      newText.forEach((newT) => {
      oldT.innerText = newT.innerText
      })
    })

</script>
      </body>
    </html>

while I'm trying to make the oldText have the same innerText

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

0

You shouldn't have a nested loop. Just loop through each oldText element and assign its .innerText to the .innerText of the corresponding newText element:

var oldText = document.querySelectorAll('.oldText')
var newText = document.querySelectorAll('.newText')
oldText.forEach((oldT, i) => {
  oldT.innerText = newText[i].innerText
})

i is the index into the newText array.

about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of using a foreach loop, you can simply use a for loop like this:

var oldText = document.querySelectorAll('.oldText')
var newText = document.querySelectorAll('.newText')
for (var i = 0; i < oldText.length; i++){
  oldText[i].innerText = newText[i].innerText;
}
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