Skip to content

Instantly share code, notes, and snippets.

@blaja blaja/.js
Created Aug 7, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.