0

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?

4
  • Is 'target1' an element id? Commented Apr 16, 2014 at 0:22
  • Makes sure target is referencing a collection of DOM elements or make sure target is declared in your code. Commented Apr 16, 2014 at 0:22
  • Not an expert here, but aren't you lacking the initialization of the target array? Commented Apr 16, 2014 at 0:22
  • Sorry, I left that part out. They are element ids... I'm using a templating engine on the back end so the way they are defined might be a little confusing for this question. Commented Apr 16, 2014 at 0:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm assuming this would have worked in normal circumstances. But I realize now my question is misleading because my logic is linked to elements being generated by a back-end templating engine. I found a solution, but it's outside the scope of this question.
How does the way the HTML is generated affect things?
@AllTheTime your question was very specific and this is the right answer to the question you asked. Certainly should be selected as the answer.
@net.uk.sweet well what I meant was that your solution didn't work in my circumstances. The element id's being targeted were generated by a for loop within the template engine so target1 target2 etc. don't actually exist when the javascript loop run. But your answer is obviously useful and correct, so I will accept it. Sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.