Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, can you extend the DOM?

Tags:

In Javascript, you can extend existing classes by using its prototype object:

String.prototype.getFirstLetter = function() {     return this[0]; }; 

Is it possible to use this method to extend DOM elements?

like image 737
nickf Avatar asked Apr 23 '09 00:04

nickf


2 Answers

I found the answer just as I was writing the question, but thought I'd post anyway to share the info.

The object you need to extend is Element.prototype.

Element.prototype.getMyId = function() {     return this.id; }; 
like image 143
nickf Avatar answered Nov 14 '22 13:11

nickf


you can extend the DOM by using the Element's prototype. However, this does not work in IE7 and earlier. You will need to extend the specific element, one at a time. The Prototype library does this. I recommend looking through the source to see exactly how it's done.

like image 34
geowa4 Avatar answered Nov 14 '22 14:11

geowa4