Skip to content

Instantly share code, notes, and snippets.

@blaja
Created August 7, 2015 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaja/44e466e9f8ec1b7d9835 to your computer and use it in GitHub Desktop.
Save blaja/44e466e9f8ec1b7d9835 to your computer and use it in GitHub Desktop.
This is how to extend Host(DOM,BOM) objects. But best to not do it at all, use wrappers.
const $ = function(selector) { return document.querySelector(selector); }; // Returns first matched element or null
const $$ = function(selector) { return document.querySelectorAll(selector); }; // Returns NodeList of matched elements or empty NodeList []
// If you want to extend HTML DOM prototype do it this way or something like this.
// Check for property or method pre-existance. Obv if JS Engine already provides property or method, you don't want to override it with your own custom one.
// This works in IE9+ or can be done even in IE8+
// Adding a new method to all HTML elements via the HTMLElement prototype
if(!HTMLElement.prototype.remove) {
// defineProperty because of enumeration
Object.defineProperty(HTMLElement.prototype, 'remove', {
value: function() {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
return this; // Allow chaining
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment