How to deal with getElementById
Recently I found code:
var d = document;
function doSomething(name){
if( typeof document.getElementById(name) != 'undefined' )
document.getElementById('innerFrame_'+name).src=document.getElementById('innerFrame_'+name).src
}
For me there are problems in this code...
- getElementById can return only element itself or null.
http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBId
var d = document;
function doSomething(name){
if( document.getElementById(name) )
document.getElementById('innerFrame_'+name).src=document.getElementById('innerFrame_'+name).src
}
Null is falsy, Element as Object is always truthy. Just use it as if condition.
- Logical problem in if condition and it's contents. I realized that function changes different element that it is testing for existence. The best option is to stop testing for existence of element by id of name, and check only for 'innerFrame_'+name. It will be faster, and if there is no inner element script will work properly.
var d = document;
function doSomething(name){
var inner = document.getElementById('innerFrame_'+name);
if( inner )
inner.src=inner.src
}
This should work much better :)
Korpo coding :)
ReplyDelete