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:
The return value of
getElementByIdwill 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
getElementsByClassNamedoes not exist in IE8 and below, you should also have a look atdocument.querySelectorAll[docs] (which at least works in IE8).