javascript - Get element within function -


i did:

var element = document.getelementbyid('myelement'); 

now want do:

 element.myfunction(); 

but have no idea how element within function. how do this?

function myfunction() { // element here? } 

you can add custom function prototype of htmlelement objects this:

htmlelement.prototype.customfunc = function(){     // within function, 'this' refer      // element called on }; 

this means element have access customfunc function method. example:

htmlelement.prototype.customfunc = function(){     console.log(this.id); };  // assuming html contains #myelement , #anotherelem: document.getelementbyid('myelement').customfunc(); // displays 'myelement' document.getelementbyid('anotherelem').customfunc(); // displays 'anotherelem' 

obviously, careful naming of function, don't want overwrite pre-existing methods or properties.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -