getElementById - how to check it


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

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

Comments

Post a Comment

Comments:

Popular posts from this blog

How to simulate slow connection (developer proxy in Node.js)

How to use NPM packages from private repositories on bitbucket