0

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.

4 Answers 4

5

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

1
  • Thx for your reply...Actually the above code needs to works only on ipad Safari...So is it fine if I use getElementsByClassName only for this browser ? Jul 20, 2011 at 7:00
5

Just replace

obj = document.getElementById('someId');

with

obj = [document.getElementById('someId')];
1
var obj = [];

if (document.getElementsByClassName('someClass'))
{
obj = document.getElementsByClassName('someClass');
}
else if (document.getElementById('someId'))
{
obj.push(document.getElementById('someId'));
}
1

you can use this

obj = [];
obj.push(document.getElementById('someId'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.