Zissle selector engine and more... 😜
Adds some methods commony known from jQuery to Elements' prototype.
Yes, prototype – better not use this in production... =)
// Create 'instance' with selector, node creation and $(document).ready() functions | |
var $ = function(selector) { return document.querySelectorAll(selector); }; | |
$.new = function(type) { return document.createElement(type); }; | |
$.ready = function(callback) { document.on('DOMContentLoaded', callback); }; | |
// Add convenience methods to Elements' prototype | |
Element.prototype.addClass = function (_class) { this.classList.add(_class); return this; }; | |
Element.prototype.removeClass = function (_class) { this.classList.remove(_class); return this; }; | |
Element.prototype.attr = function (attr, val) { this.setAttribute(attr, val); return this; }; | |
Element.prototype.text = function (text) { this.textContent = text; return this; }; | |
Element.prototype.html = function(html) { this.innerHTML = html; return this; }; | |
Element.prototype.on = function (event, callback, options) { this.addEventListener(event, callback, options); return this; }; | |
Element.prototype.empty = function () { while (this.lastChild) { this.removeChild(this.lastChild); } return this; }; | |
// (Cheap) polyfill for append() as it's very convenient and supplied by jQuery, too | |
if (!Element.prototype.append) { | |
Element.prototype.append = function () { | |
var that = this; | |
var args = [].slice.call(arguments); | |
args.forEach(function(item) { | |
if (item instanceof Node) that.appendChild(item); | |
else that.appendChild(document.createTextNode(''+item)); | |
}); | |
}; | |
} | |
// Assign $ to window so it's available globally | |
window.$ = $; |