Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Augmenting the prototype of DOM element nodes?

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?

like image 433
Šime Vidas Avatar asked Nov 16 '10 11:11

Šime Vidas


People also ask

What is element node in DOM?

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.

How do you add nodes in DOM tree?

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.

Which of the method is used to create your elements in Javascript DOM?

The createElement() method creates an element node.

How do you make a DOM string?

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.


1 Answers

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.

like image 72
Andy E Avatar answered Sep 29 '22 17:09

Andy E