tags:

views:

57

answers:

3

I need to access elements in html file using javascript, their names are like arr_1, arr_2, arr_3, i wish to use a loop to dynamically create the id then to access them like below:

for(var i=0; i< 10; i++) {
  var id = "arr_" + i;

  $document.getElementById('id')....

}

but it doesn't work. i remember there is an function to allow me do that, anyone know what that is?

+1  A: 

change

$document.getElementById('id')

to

$document.getElementById(id)
Cory Petosky
Why the dollar sign?
John
It was in his original code -- I was fixing his syntax. He passed a literal string, when he meant to pass the variable `id`. $document is a valid identifier in JS and I didn't look beyond that -- though I agree it's probably a mistake. CMS's answer expressed this more clearly.
Cory Petosky
+1  A: 
for (var i = 0; i < 10; i++) {
  var obj = document.getElementById("arr_" + i);
  obj.style.border = "1px solid red";
}
John
+2  A: 

You don't need the dollar sign preceding document, and you should pass your id variable to the getElementById function, not a string containing 'id':

for(var i=0; i< 10; i++) {
  var id = "arr_" + i;
  var element = document.getElementById(id);
  // work with element
}

You might also want to check if getElementById actually found your element before manipulating it, to avoid run-time errors:

if (element) {
  element.style.color = '#ff0000';
}
CMS
+1 for mentioning the difference between a string literal and a variable.
darkporter