Skip to content

Instantly share code, notes, and snippets.

@1000ch
Last active December 16, 2015 21:39
Show Gist options
  • Save 1000ch/5501425 to your computer and use it in GitHub Desktop.
Save 1000ch/5501425 to your computer and use it in GitHub Desktop.
const rx = {
id: /^#([\w\-]+)$/,
className: /^\.([\w\-]+)$/,
tagName: /^[\w\-]+$/,
name: /^\[name=["']?([\w\-]+)["']?\]$/
};
function $(selector, context) {
let result;
let m;
if(!context || !context.querySelector) {
context = document;
}
if (m = rx.id.exec(selector)) {
let element = document.getElementById(m[1]);
result = element ? [element] : [];
} else if (m = rx.className.exec(selector)) {
result = context.getElementsByClassName(m[1]);
} else if (m = rx.tagName.exec(selector)) {
result = context.getElementsByTagName(m[1]);
} else if (m = rx.name.exec(selector)) {
result = context.getElementsByName(m[1]);
} else {
result = context.querySelectorAll(selector);
}
return Array.of(result);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment