getElementById - how to check it

pre { background-color: rgba(46,236,106, 0.2); }  

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



Share on Hacker News
Share on LinkedIn


← Home


Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.