Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Forked from ofca/$.3.js
Created May 14, 2013 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/5577276 to your computer and use it in GitHub Desktop.
Save james2doyle/5577276 to your computer and use it in GitHub Desktop.
// based on https://gist.github.com/Potfur/5576225 & https://github.com/james2doyle/saltjs
// more info: https://plus.google.com/109231487156400680487/posts/63eZzzrBSb6
window.$ = function(s) {
var c = {
'#': 'ById',
'.': 'sByClassName',
'@': 'sByName',
'=': 'sByTagName'}[s[0]];
return document[c?'getElement'+c:'querySelectorAll'](s.slice(1))
};
@pwFoo
Copy link

pwFoo commented Feb 26, 2017

Nice short function, but it isn't similar to jQuery selectors (prefix "=") and can't parse "complex selectors" ('#three > .class2' -> returns NULL).

$.3.js size:
Input: 218 bytes
Output: 162 bytes
Gzip: 155 bytes

custom function:
input: 775 bytes
Output: 216 bytes
Gzip: 187 bytes

function sel(selector, context) {
    context = context || document;
    var type = selector.charAt(0),
        selectorValue = selector.substr(1),
        singleValue = /^[\w\*\-_\.\#]+$/;
        //singleValue = /^(.?\w+|\*)$/;//,
        //multiValue = /^.?\w+(\.|,)?\w+?$/;

    if (singleValue.exec(selector)) {   // simple single word selector?
        if (type === '#') { // single ID
            return [context.getElementById(selectorValue)];
        } else if (type === '.') {  // single CLASS
            return context.getElementsByClassName(selectorValue);
        } else {    // single TAG NAME
            return context.getElementsByTagName(selector);
        }
    } else {    // complex selector...
        return context.querySelectorAll(selector);
    }
}

It isn't deeply tested yet, but seems to perform nice.
https://jsperf.com/custom-function-vs-james2doyle-vs-jquery

Have You any new / improved selector function? Any suggestions about my function how to improve?

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