Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  95] [ 7]  / answers: 1 / hits: 23346  / 14 Years ago, sat, february 19, 2011, 12:00:00

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?


More From » function

 Answers
55

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;
}

[#93665] Thursday, February 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
valentinam

Total Points: 166
Total Questions: 117
Total Answers: 81

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;