====== typeof ======
A less-known operator in JavaScript is the typeof operator. It tells you what type of data you're dealing with. Makes sense, huh? Let's look at some examples:
var BooleanValue = true;
var NumericalValue = 354;
var StringValue = "This is a String";
alert(typeof BooleanValue) // displays "boolean"
alert(typeof NumericalValue) // displays "number"
alert(typeof StringValue) // displays "string"
===== checking for existence =====
if( typeof addEvent != 'undefined' ){
// addEvent method exists, and is okay to use here
}
===== typeof with document.getElementById =====
Do NOT use the following:
if( typeof document.getElementById('someElementId') != 'undefined' ){
// do something with element
}
...because getElementById() is a method which incorporates its own typeof checking. If an element doesn't exist, it will still return 'Object', because null is what is returned and it is an Object in itself. Instead, simply do this:
if( document.getElementById('someElementId') != null ){
// do something with element
}
// or
var el = document.getElementById('someElementId');
if( el ){
// do something with element
}