Christopher Reid
Christopher Reid

Reputation: 4484

Javascript - Appending for loop index to a variable inside loop

I'm trying to target a list of elements using a for loop:

for(var i = 1; i < 5; ++i){
    console.log(i)
    target[i].classList.remove('redText')
    anchor[i].classList.remove('redText')
}

The expected result is:

target1.classList.remove('redText')
anchor1.classList.remove('redText')
target2.classList.remove('redText')
anchor2.classList.remove('redText')

....etc.

in the console I get

ReferenceError: target is not defined

Which means the index is not being appended to target and anchor.

Is this possible to accomplish?

Upvotes: 0

Views: 290

Answers (1)

net.uk.sweet
net.uk.sweet

Reputation: 12431

This is what you're looking for:

for(var i = 1; i < 5; ++i){
    console.log(i)
    document.getElementById('target' + i).classList.remove('redText')
    document.getElementById('anchor' + i).classList.remove('redText')
}

Fiddle.

Upvotes: 2

Related Questions