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'

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

👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP