jQuery Like Selector in Pure JavaScript

April 17, 2016

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'
  ](s.slice(1));
};

It’s based on the Michal Wachowski’s gist

And here’s how to use it.

// get by id
$('#iddiv');
// get by class name
$('.classdiv');
// get by element name
$('@namediv');
// get by element tag name
$('=div');
// get element by query selector
$('*div div.inside');
// getAttribute of name
$('#iddiv').getAttribute('name');
// getAttribute of name from nodelist
$('.classdiv')[0].getAttribute('name');

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP