Skip to content

Instantly share code, notes, and snippets.

@wall-e-08
Last active July 26, 2018 10:56
Show Gist options
  • Save wall-e-08/84496340a6838f7f8c23c0cdefc82b1f to your computer and use it in GitHub Desktop.
Save wall-e-08/84496340a6838f7f8c23c0cdefc82b1f to your computer and use it in GitHub Desktop.
jquery dollar sign selector in plain js
window.$ = function(selector) {
var selectorType = 'querySelectorAll';
if (selector.indexOf('#') === 0) { //if id selector
selectorType = 'getElementById';
selector = selector.substr(1, selector.length);
}
return document[selectorType](selector);
};
//usage:
var id_el = $('#id_selector'); //return one object
var cls_el = $('.class_selector'); //return array object
id_el.style.fontSize = '100px'; //correct
//cls_el.style.fontSize = '100px'; //incorrect
cls_el[0].style.fontSize = '100px'; //correct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment