New blog domain: kula.blog

It's still work in progress but new posts will be published on  https://kula.blog/ Thanks to 11ty base blog RSS is working from the start so it should be easy to add to your reader if you still use any :) If now then I hope you can sign up to the newsletter where I'll be publishing new posts and interesting articles to it from time to time. Please use  kula.blog  from now on.

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 use NPM packages from private repositories on bitbucket

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