0

I have several elements with the className "error", I need to dynamically add a unique id to each one. From other questions on stack I have put together the following code but it doesn't seem to work.

function setErrorId() {
var errorClass = document.getElementsByClassName('error');
for (i = 0; i < errorClass.length; i++) {
    var idName = 'error' + i;
    errorClass[i].id = idName;
}
6
  • Do you get an error? (Also… why?) Commented Oct 27, 2013 at 16:33
  • That seems it should work fine, can you post a fiddle? Commented Oct 27, 2013 at 16:33
  • missing a closure } Commented Oct 27, 2013 at 16:35
  • i is an undefined variable Commented Oct 27, 2013 at 16:35
  • code seem right, you can check if errorClass get assignment with alert(errorClass). also "for (i;" normally should be "for (var i;" Commented Oct 27, 2013 at 16:37

2 Answers 2

1

you have an undefined variable i. just define it but other than that your fine.

function setErrorId () {
 var errorClass = document.getElementsByClassName('error')
   , i = 0
   , l = errorClass.length;

  while (i < l) {
    errorClass[i].id = 'error' + i++;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You're missing a }

like this:

function setErrorId() {
    var errorClass = document.getElementsByClassName('error');
    for (i = 0; i < errorClass.length; i++) {
    var idName = 'error' + i;
    errorClass[i].id = idName;
    }
}

Comments

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.