Skip to content

Instantly share code, notes, and snippets.

@lilianchisca
Created June 8, 2013 19:55
Show Gist options
  • Save lilianchisca/5736375 to your computer and use it in GitHub Desktop.
Save lilianchisca/5736375 to your computer and use it in GitHub Desktop.
DOM Selector Lib. by https://github.com/james2doyle
window.$ = function (selector) {
// an object containing the matching keys and native get commands
var matches = {
'#': 'getElementById',
'.': 'getElementsByClassName',
'@': 'getElementsByName',
'=': 'getElementsByTagName',
'*': 'querySelectorAll'
}[selector[0]]; // you can treat a string as an array of characters
// now pass the target without the key
return (document[matches](selector.slice(1)));
};
// probably the most useful and allows $('#iddiv').find('.inside')
Element.prototype.find = Element.prototype.querySelectorAll;
// another useful one for doing $('.inside').forEach()
NodeList.prototype.forEach = Array.prototype.forEach;
// $().attr('prop', 'value') support
Element.prototype.attr = function (name, value) {
if (value) {
this.setAttribute(name, value);
} else {
return this.getAttribute(name);
}
};
// $().css('prop', 'value') support
Element.prototype.css = function (prop, value) {
if (value) {
this.style[prop] = value;
} else {
return this.style[prop];
}
};
// $().on('event', function(el){});
Element.prototype.on = function (evt, fn) {
this['on' + evt] = fn.bind(this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment