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...
- 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 :)
Want to learn more?
Sign up to get a digest of my articles and interesting links via email every month.