Javascript : How to create global functions & variables

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

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

I’m not talking about this:

  • Access element in eventListener by element index in javascript
  • Track ALL clicked elements using JavaScript
  • Why does innerHTML not change src of an image?
  • JScript Check if element exists and remove it
  • How can I count the number of elements in a DOM?
  • How to create and style div on JavaScript
  • 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?

  • Append elements with childs and classes using jQuery
  • Counting the occurrences / frequency of array elements
  • How to get child element by ID in JavaScript?
  • add VML elements (images) with javascript
  • AngularJS directive - setting order for multiple directive elements (not priority for directives, but priority for the elements)
  • width() and height() for modern browsers without jQuery
  • 5 Solutions collect form web for “Javascript : How to create global functions & variables”

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

    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.

    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.

    Try

    Object.prototype.myNeweFunction=function(){
     doSomthing..
    }
    

    For example:

    HTMLAnchorElement.prototype.click = function () {
        alert('HAI!');
    };
    
    document.links[0].click();
    

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