12

In JavaScript, you will often see functions which say document.getElementById("element").someFunction(); or $("element").someFunction(); instead of someFunction($("element"));. Where someFunction(element) looks a little like the following code.

someFunction(element) {
    //element.doSomething();
}

My question is how do you make a function which manipulates the element it is attached to instead of manipulating an element passed through as an argument?

Dan
  • 7,286
  • 6
  • 49
  • 114

2 Answers2

7

You can achieve it using prototype

// `getElementById` returns a `Element` object so extend it's prototype
Element.prototype.someFunction = function(){
   // this.somethig
}

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

Element.prototype.someFunction = function() {
  console.log(this.value)
}

document.getElementById("element").someFunction();
<input value="abc" id="element" />

Note : It's really bad practice to extend prototype of native object.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 3
    It's also worth noting that extending a built in object's prototype generally not recommended. – Seth Jul 28 '16 at 19:00
  • @Seth What would you recommend I do? Is it better to leave it as `someFunction(element)`? – Dan Jul 28 '16 at 19:06
  • 1
    @Dan Use `someFunction(element)` ..... use `prototype` only for polyfil option of new methods like `forEach, find, some, etc...`..... – Pranav C Balan Jul 28 '16 at 19:08
2

You are looking for prototypes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

element.prototype.someFunction = function(){
  this.doSomething(); // this refers to element
}
Hans Strausl
  • 605
  • 5
  • 11