开发者

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.


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


Check the length of the array. jQuery always returns a jquery instance, with an array of the matched elements.

$(idString).length > 0


if($("#id").length){}


jQuery always returns an object (an array). If the element with that ID is not found, then the length of the returned array will be 0.

var isItDefined = ($(idString).length > 0);

Update: for prototype, you should check for null to see if the object is found

var isItDefined = ($(idString) !== null);


$(), in jQuery, will always return an object. Try this instead:

var isItDefined = (typeof document.getElementById(idString) != 'undefined');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜