开发者

how to access element whose id is variable

I need to access elements in html file using javascript, thei开发者_StackOverflow社区r 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?


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';
}


for (var i = 0; i < 10; i++) {
  var obj = document.getElementById("arr_" + i);
  obj.style.border = "1px solid red";
}


change

$document.getElementById('id')

to

$document.getElementById(id)


Since this question was published and answered quite correctly several times by using document.getElementById(id), another contender has entered the fray, querySelector, which takes any valid CSS selector and returns the first matched element.

Note that because querySelector takes a CSS selector, selecting an ID requires prefixing the ID with #.

for(var i=0; i< 10; i++) {
  // Added the # here in the id variable.
  var id = "#arr_" + i;
  // assuming $document is a reference to window.document in the browser...
  var element = $document.querySelector(id);
  if (element) {
    // do something with element
  }
}

getElementById is typically faster than querySelector (in some browsers, twice as fast), which makes sense, since it doesn't have to invoke the CSS subsystem to find the element.

However, the option exists, and Stack Overflow is nothing if not thorough when answering questions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜