Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function to go after an element [duplicate]

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?

like image 337
Dan Avatar asked Jul 28 '16 18:07

Dan


2 Answers

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.

like image 173
Pranav C Balan Avatar answered Nov 15 '22 21:11

Pranav C Balan


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
}
like image 24
Hans Strausl Avatar answered Nov 15 '22 19:11

Hans Strausl