Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save WebReflection/c92c8d9223449d23e09c to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/c92c8d9223449d23e09c to your computer and use it in GitHub Desktop.
A jQuery like function with :first built in optimization, will return an Array regardless it's one element search only for consistency.
function $(CSS, parentNode) {
// @link http://webreflection.blogspot.com/2014/05/134-bytes-for-optimized-and-very-basic.html
var el = parentNode || document,
first = CSS.lastIndexOf(':first') === CSS.length - 6,
query = first ?
el.querySelector(CSS.slice(0, -6)) :
el.querySelectorAll(CSS);
return first ?
(query ? [query] : []) :
Array.prototype.slice.call(query);
}
@WebReflection

Copy link
Copy Markdown
Author

examples

// basic usage
$('div');               // same as document.querySelectorAll('div')
$('div:first');         // same as document.querySelector('div')
$('p', div);            // same as div.querySelectorAll('p')
$('p:first', div);      // same as div.querySelector('p')

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