Search code examples
javascriptdomprototypejsundefinedtypeof

Using Javascript's typeof on DOM elements to check undefined (IE problem)


I want to iterate over a list of DOM elements (check boxes) and keep going as long as this list defined. The elements are 'c1r1', 'c1r2', 'c1r3', etc. Once I hit an undefined one, I stop. The problem seems to be using typeof with DOM elements.

Here's the offending code:

function domIsDefined(idString){
    alert(idString);
    var isItDefined = (typeof $(idString) != 'undefined');
    alert(isItDefined);
    return isItDefined;
}
...
for(i=1; domIsDefined('c1r' + i); i++){
    if($('c1r' + i).checked==true){
        // do stuff
    }
}

The crux of the problem is this line:

var isItDefined = (typeof $(idString) != 'undefined');

The problem, as I found out, is that typeof $(idString) always returns object, whether it is defined or not. Is there any good way to do this sort of thing? I guess I'll put in a try catch and check the .checked property early, but that feels disgusting.


Solution

  • function domIsDefined(idString){
        return !!document.getElementById(idString);
    }