Last Updated: February 25, 2016
·
765
· boopathi

jQuery like selector with querySelector

;(function(w, d, undefined){
  'use strict';

  var $ = function (e) {
    var firstChar = e.charAt(0);
    if (firstChar === '#') {
      return d.querySelector(e);
    } else if (firstChar === '.') {
      return d.querySelectorAll(e);
    } else {
      return d.getElementById(e);
    }
  };
  w.$ = $;
})(window, document);

console.log($('#my-element'));  // querySelector()
console.log($('.my-element')); // querySelectorAll()
console.log($('my-element')); // getElementById()