javascript 将 getElementById 返回值视为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6757964/
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
Treat getElementById return value as array
提问by testndtv
I have a Javascript as follows;
我有一个 Javascript 如下;
if (document.getElementsByClassName('someClass'))
{
obj = document.getElementsByClassName('someClass');
}
else if (document.getElementById('someId'))
{
obj = document.getElementById('someId');
}
Now there is a for loop which acts on this "obj"
现在有一个作用于这个“obj”的 for 循环
for(i=0; i<obj.length;i++){
obj[i].addEventListener() // Pseudo code shown here
}
The issue is this works fine if obj
is returned as an array i.e. from document.getElementsByClassName
.
问题是,如果obj
作为数组返回,即从document.getElementsByClassName
.
But if document.getElementById('someId')
is true, it does not return an array and the for loop fails to execute.
但如果document.getElementById('someId')
为真,则不会返回数组并且 for 循环无法执行。
How can I fix this issue, given that I cannot do anything to the HTML code itself?
鉴于我无法对 HTML 代码本身做任何事情,我该如何解决这个问题?
Thank you.
谢谢你。
回答by Felix Kling
You can simply create an array:
您可以简单地创建一个数组:
else if (document.getElementById('someId')) {
obj = [document.getElementById('someId')]; // note the array literal
}
The return value of getElementById
will alwaysbe a DOM element, so you cannot change that. IDs are supposed to be unique, so even if you have several elements with the same ID, it will return only one of them.
的返回值getElementById
将始终是 DOM 元素,因此您无法更改它。ID 应该是唯一的,因此即使您有多个具有相同 ID 的元素,它也只会返回其中一个。
Given that getElementsByClassName
does not exist in IE8 and below, you should also have a look at document.querySelectorAll
[docs](which at least works in IE8).
鉴于getElementsByClassName
在 IE8 及更低版本中不存在,您还应该查看document.querySelectorAll
[docs](至少在 IE8 中有效)。
回答by Daniel O'Hara
Just replace
只需更换
obj = document.getElementById('someId');
with
和
obj = [document.getElementById('someId')];
回答by Vivek
var obj = [];
if (document.getElementsByClassName('someClass'))
{
obj = document.getElementsByClassName('someClass');
}
else if (document.getElementById('someId'))
{
obj.push(document.getElementById('someId'));
}
回答by Fahad Hussain
you can use this
你可以用这个
obj = [];
obj.push(document.getElementById('someId'));