Treat Getelementbyid Return Value As Array
I have a Javascript as follows; if (document.getElementsByClassName('someClass')) { obj = document.getElementsByClassName('someClass'); } else if (document.getElementById('someId')
Solution 1:
You can simply create an array:
elseif (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
(which at least works in IE8).
Solution 2:
Just replace
obj = document.getElementById('someId');
with
obj = [document.getElementById('someId')];
Solution 3:
var obj = [];
if (document.getElementsByClassName('someClass'))
{
obj = document.getElementsByClassName('someClass');
}
elseif (document.getElementById('someId'))
{
obj.push(document.getElementById('someId'));
}
Solution 4:
you can use this
obj = [];
obj.push(document.getElementById('someId'));
Post a Comment for "Treat Getelementbyid Return Value As Array"