将getElementById返回值作为数组处理 [英] Treat getElementById return value as array
问题描述
我有一个Javascript,如下所示:
if(document.getElementsByClassName('someClass'))
{
obj = document.getElementsByClassName('someClass');
}
else if(document.getElementById('someId'))
{
obj = document.getElementById('someId');
}
现在有一个对这个obj行为的for循环>
for(i = 0; i< obj.length; i ++){
obj [i] .addEventListener()//这里显示的伪代码
}
如果 obj
作为数组返回,即从 document.getElementsByClassName
。
但是 document.getElementById('someId')
是true,它不返回数组,而for循环无法执行。
谢谢。
您可以简单地创建一个数组:
else if .getElementById('someId')){
obj = [document.getElementById('someId')]; //注意数组文字
}
返回值 getElementById
将永远成为一个DOM元素,所以你不能改变。 ID应该是唯一的,所以即使你有几个具有相同ID的元素,它只返回其中的一个。
鉴于在IE8及以下版本中不存在getElementsByClassName
,您还应该查看 document.querySelectorAll
[docs] (至少在IE8中工作) p>
I have a Javascript as follows;
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"
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
.
But if document.getElementById('someId')
is true, it does not return an array and the for loop fails to execute.
How can I fix this issue, given that I cannot do anything to the HTML code itself?
Thank you.
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 always be 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.
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).
这篇关于将getElementById返回值作为数组处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!