I know how to add new methods to every object - by augmenting the Object's prototype:
Object.prototype.foo = function() { };
But, is it possible to define new methods for DOM element nodes only? Do DOM element node objects have a prototype? Or is there maybe a prototype for DOM nodes in general?
Or do prototype objects only exist for built-in objects?
An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...). The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling.
Add a Node - appendChild() The appendChild() method adds a child node to an existing node. The new node is added (appended) after any existing child nodes. Note: Use insertBefore() if the position of the node is important.
The createElement() method creates an element node.
The createElement() method is used for creating elements within the DOM. It accepts two parameters, a tagName which is a string that defines the type of element to create, and an optional options object that can be used to modify how the element is created.
Yes, but not in all browsers. Internet Explorer 8 supports DOM prototypes (to a certain extent), as do Firefox, Chrome, Opera and Safari.
HTMLElement.prototype.toggle = function () {
this.style.display = this.style.display == 'none' ? '' : 'none';
}
Many consider it bad practice to extend DOM objects via their prototype. Kangax has a great article on the subject: http://perfectionkills.com/whats-wrong-with-extending-the-dom/. However, DOM prototypes allow us to implement standards-based methods in environments that don't support them yet, much like shims for ECMAScript 5th Edition methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With