Skip to content

Instantly share code, notes, and snippets.

@jonaskuske
Last active December 6, 2018 01:01
Show Gist options
  • Save jonaskuske/fe93e780cbd5af4db4794df55fe5badd to your computer and use it in GitHub Desktop.
Save jonaskuske/fe93e780cbd5af4db4794df55fe5badd to your computer and use it in GitHub Desktop.
qJerry – convenience methods for DOM manipulation

qJerry

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.$ = $;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment