Dan Dan - 4 months ago 13
jQuery Question

How to make a function to go after an element

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?

Answer

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.