Created
September 12, 2014 09:25
-
-
Save bloodyowl/00a533f3aa277d217c92 to your computer and use it in GitHub Desktop.
simple selector
This file contains hidden or 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 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 = $ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
simple DOM selector
$(selector[, context=document]) > array
returns an array containing the elements matching the given selector within the given contextNode