Published on

jQuery Like Selector in Pure JavaScript


Here's a quick post on how to select elements with the native HTML5 Selectors.

window.$ = function (s) {
  return document[
      '#': 'getElementById',
      '.': 'getElementsByClassName',
      '@': 'getElementsByName',
      '=': 'getElementsByTagName',
    }[s[0]] || 'querySelectorAll'

It's based on the Michal Wachowski's gist

And here's how to use it.

// get by id
// get by class name
// get by element name
// get by element tag name
// get element by query selector
$('*div div.inside');
// getAttribute of name
// getAttribute of name from nodelist