8

I would like to create a new function that I can use on elements, like this:

document.getElementById("element").myNewFunction();

I'm not talking about this:

document.getElementById("element").myNewFunction = function(){
   doSomething...
}

Because this works on that element only, but how should I create global function what I can use on all elements like the ones what are built in to JavaScript?

gotqn
  • 42,737
  • 46
  • 157
  • 243
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • 1
    it' bad style i think. Instead of this, create some hash where key is id of the element, and the value - function. i will be more simple to understand and use – Falcon Feb 19 '11 at 20:51

5 Answers5

9

Use Element's prototype to extend its functionality:

Element.prototype.myNewFunction = function() { 
      // your code...
};

Now you can call this method on any element object.

Edit: I've just had a quick check around, and it appears that this will not work for IE7 and below, and IE8 might be iffy.

Edit 2: Also as Eli points out it's probably not best practice to extend objects you don't own. Given this and shaky IE support you might want to consider a simple procedural function:

function myFunction(element) {
  // your code...

  // which may or may not return an object or value
  return blah;
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
Richard H
  • 38,037
  • 37
  • 111
  • 138
  • Hmm, element's prototype? so there are prototypes for all kinds of object types? I never really understood how prototypes are working :) – Adam Halasz Feb 19 '11 at 20:33
  • Read http://javascript.crockford.com/prototypal.html to understand Prototypal inheritance – Zimbabao Feb 19 '11 at 20:35
5

See this question: In Javascript, can you extend the DOM?.

While it is possible to do, its generally considered bad practice to change the functionality of objects you don't own.

Community
  • 1
  • 1
Eli
  • 17,397
  • 4
  • 36
  • 49
1

Prototype (the library) does this, extends the native (built-in) DomElement class by adding methods to its prototype. It doesn't work in old IEs though so I'd recommend against it.

jpsimons
  • 27,382
  • 3
  • 35
  • 45
1

Try

Object.prototype.myNeweFunction=function(){
 doSomthing..
}
Zimbabao
  • 8,150
  • 3
  • 29
  • 36
1

For example:

HTMLAnchorElement.prototype.click = function () {
    alert('HAI!');
};

document.links[0].click();

Figure out right object to extend by querying document.getElementById("element").constructor

Free Consulting
  • 4,300
  • 1
  • 29
  • 50