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

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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