Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!