Skip to content

Instantly share code, notes, and snippets.

@zzen
Forked from steida/gist:204554
Created February 9, 2010 15:06
Show Gist options
  • Save zzen/299289 to your computer and use it in GitHub Desktop.
Save zzen/299289 to your computer and use it in GitHub Desktop.
/*
* Sugar for type detection working across frames and browsers ;)
*
* Detected types
*
* 'arguments', 'array', 'boolean', 'date', 'document', 'element', 'error', 'fragment',
* 'function', 'nodelist', 'null', 'number', 'object', 'regexp', 'string', 'textnode',
* 'undefined', 'window'
*
* Copyright (c) 2009 Daniel Steigerwald (http://daniel.steigerwald.cz), Mit Style License
*/
var $type = (function() {
var toString = Object.prototype.toString,
toStrings = {},
nodeTypes = { 1: 'element', 3: 'textnode', 9: 'document', 11: 'fragment' },
types = 'Arguments Array Boolean Date Document Element Error Fragment Function NodeList Null Number Object RegExp String TextNode Undefined Window'.split(' ');
for (var i = types.length; i--; ) {
var type = types[i], constructor = window[type];
if (constructor) {
try { toStrings[toString.call(new constructor)] = type.toLowerCase(); }
catch (e) { }
}
}
return function(item) {
return item == null && (item === undefined ? 'undefined' : 'null') ||
item.nodeType && nodeTypes[item.nodeType] ||
typeof item.length == 'number' && (
item.callee && 'arguments' ||
item.alert && 'window' ||
item.item && 'nodelist') ||
toStrings[toString.call(item)];
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment