How to create a own function | Sololearn: Learn to code for FREE!

+10

How to create a own function

I want to create own function For example : element.myFunction() I want to create own function like pop(), push(), setattribute I don't know what type of function it is called so i am unable to define my problem But i can give u some example for example I create a function function myFun(){/* some code*/ } Now i want to use with a element element.myFun()

9/2/2021 2:11:11 PM

Beauty

15 Answers

New Answer

+15

HrCoder you must define prototype for the HTMLDivElement object .. just like this window.onload=()=>{ var element = document.querySelector('div') HTMLDivElement.prototype.myFunction=function(){ this.style.background="red" } // calling function like this element.myFunction(); }

+5

just do this element.prototype.myFunction=function(){ // your custom function ( u can also use this. to access the object's properties ) }

+5

Prashanth Kumar can i use only HTMLElement because HTMLDivElement will work only on div element

+3

Do you want to call a function on any Element ?? If yes Then, this can be helpful:- https://code.sololearn.com/W0bEHElAUqoO/?ref=app

+2

Then what you want to do is binding a function to html element?

+2

HrCoder you can do something like that: const element = { name: "rupali", favLang: "JavaScript", myFunction: function(){ console.log("I'm a function :D") } } element.myFunction();

+2

rupali i want like this document.querySelector("div").myFun() define my myFun Function myFun(){ This.style.fontSize="20rem" } i want a function that works with an element When ever i call this function with an element make that element font-size as 20rem (Styling an element is just for an example i also want to do othere this with this )

+2

Even I had to do this for my own array utility methods. Yes, prototype is the way to go in Javascript 👍 https://code.sololearn.com/WG7GFmJZc1wQ/?ref=app

+1

Maybe you want to create an object or write your own class? Is the element an html element or a javascript element?

+1

HrCoder yes 👍🏻👍🏻you can use it on any object

+1

Prashanth Kumar i want to learn more about this will u please provide to some good source

0

Lisa Html element is there any example

0

Lisa okay suppose i create a class but how to attach with an element element.myFunctio()

0

Is it something like this you're looking for? bind() https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method

0

Prashanth Kumar it gives an error https://code.sololearn.com/WX5vhjwRmGdo/?ref=app