Javascript 如何访问id可变的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2331086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:49:16  来源:igfitidea点击:

how to access element whose id is variable

javascript

提问by Ohana

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:

我需要使用 javascript 访问 html 文件中的元素,它们的名称类似于arr_1, arr_2, arr_3,我希望使用循环来动态创建 id 然后访问它们,如下所示:

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?

但它不起作用。我记得有一个功能可以让我这样做,有人知道那是什么吗?

回答by CMS

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

您不需要前面的美元符号document,您应该将id变量传递给getElementById函数,而不是包含'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 getElementByIdactually found your element before manipulating it, to avoid run-time errors:

您可能还想getElementById在操作之前检查是否确实找到了您的元素,以避免运行时错误:

if (element) {
  element.style.color = '#ff0000';
}

回答by John

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

回答by Cory Petosky

change

改变

$document.getElementById('id')

to

$document.getElementById(id)

回答by Heretic Monkey

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.

由于此问题已发布并通过使用多次正确回答document.getElementById(id),因此另一个竞争者加入了竞争,querySelector,它接受任何有效的 CSS 选择器并返回第一个匹配的元素。

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

请注意,由于querySelector采用 CSS 选择器,因此选择 ID 需要在 ID 前加上#.

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

getElementByIdis 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.

getElementById通常比querySelector(在某些浏览器中,快两倍),这是有道理的,因为它不必调用 CSS 子系统来查找元素。

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

但是,该选项存在,如果在回答问题时不彻底,Stack Overflow 就不算什么。