Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created September 12, 2014 09:25
Show Gist options
  • Save bloodyowl/00a533f3aa277d217c92 to your computer and use it in GitHub Desktop.
Save bloodyowl/00a533f3aa277d217c92 to your computer and use it in GitHub Desktop.
simple selector
var nativeSlice = Array.prototype.slice
var CAN_SLICE_NODELISTS = function(){
try {
nativeSlice.call(document.documentElement.children)
return true
} catch(e){
return false
}
}()
var ACCEPTED_NODETYPES = {
1 : null,
9 : null
}
function createArray(nodeList) {
if(CAN_SLICE_NODELISTS) {
return nativeSlice.call(nodeList)
}
var index = -1
var length = nodeList.length
var result = Array(length)
while(++index < length) {
result[index] = nodeList[index]
}
return result
}
function $(selector /*, context */){
var context = arguments[1]
if(typeof selector != "string") {
throw new TypeError("selector must be a string")
}
if(arguments.length < 2) {
context = document
}
if(!context || !ACCEPTED_NODETYPES.hasOwnProperty(context.nodeType)) {
return []
}
return createArray(context.querySelectorAll(selector))
}
module.exports = $
@bloodyowl
Copy link
Author

simple DOM selector

$(selector[, context=document]) > array

returns an array containing the elements matching the given selector within the given contextNode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment