Created
April 22, 2014 14:51
-
-
Save Skateside/11182222 to your computer and use it in GitHub Desktop.
Playing with simply but highly-efficient DOM selections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dom = { | |
toArray: function (nodes) { | |
var array = []; | |
if (nodes) { | |
array = typeof nodes.length === 'number' ? | |
Array.prototype.slice.call(nodes) : | |
[nodes] | |
} | |
return array; | |
}, | |
byId: function (id, context) { | |
var start = context || document; | |
return this.toArray(start.getElementById(id)); | |
}, | |
byClass: function (className, context) { | |
var start = context || document; | |
return this.toArray(start.getElementsByClassName(className)); | |
}, | |
byTag: function (tag, context) { | |
var start = context || document; | |
return this.toArray(start.getElementsByTagName(tag)); | |
}, | |
byQuery: function (query, context) { | |
var start = context || document; | |
return this.toArray(start.querySelectorAll(tag)); | |
}, | |
get: function (query, context) { | |
var found = null, | |
name = query.slice(1); | |
if (/^#\w+$/.test(query)) { | |
found = this.byId(name, context); | |
} else if (/^\.\w+$/.test(query)) { | |
found = this.byClass(name, context); | |
} else if (/^\w+$/.test(query)) { | |
found = this.byTag(query, context); | |
} else { | |
found = this.byQuery(query, context); | |
} | |
return found; | |
} | |
}; | |
// Compare: | |
dom.toArray(document.getElementById('test')); | |
dom.toArray(document.getElementsByClassName('test')); | |
dom.toArray(document.getElementsByTagName('test')); | |
dom.toArray(document.querySelectorAll('test')); | |
dom.get('#test'); | |
dom.get('.test'); | |
dom.get('test'); | |
dom.get('div#test'); | |
// dom.toArray([native code]) should be faster than dom.get() but important is | |
// the comparison between dom.toArray(document.querySelectorAll()) and dom.get() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment