Skip to content

Instantly share code, notes, and snippets.

@yuya
Last active December 18, 2015 09:49
Show Gist options
  • Save yuya/5763971 to your computer and use it in GitHub Desktop.
Save yuya/5763971 to your computer and use it in GitHub Desktop.
function $(selector, context) {
context = context || document;
var firstChar = selector[0],
nameOnly = selector.substring(1, selector.length),
maybeId = firstChar === "#",
maybeClass = firstChar === ".",
isSimple = /^[\w-]*$/.test(nameOnly),
qsaRe = /^(.+[\#\.\s\[\*>:,]|[\[:])/,
element =
maybeId && isSimple ?
context.getElementById(nameOnly) :
maybeClass && isSimple ?
context.getElementsByClassName(nameOnly) :
qsaRe.test(selector) ?
context.querySelectorAll(selector) :
context.getElementsByTagName(selector)
;
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment