Home > Net >  Specify an HTML element before the custom function through dot (like element.myFunction)?
Specify an HTML element before the custom function through dot (like element.myFunction)?

Time:03-31

So, I have my custom function that I want to do something with the specified element, like:

const element = document.querySelector('some-element')
element.myFunc()

function myFunc() {
//do something with element specified before the dot
}

But this gives me an error that this is not a function. The only thing I can do is to specify the element as an argument of my function, like that:

const element = querySelector('some-element')
myFunc(element)

function myFunc(element) {
   //do something with element
}

What do I need to be able to use my function through the dot, like element.myFunction() ?

CodePudding user response:

There's nothing inherently wrong with just passing the element to the function. But if you really want to do this...

querySelector returns an Element. So you could add your function to the Element prototype. For example:

Element.prototype.myFunc = function () {
  console.log(this);
};

const element = document.querySelector('#some-element')
element.myFunc();
<div id="some-element">test</div>

It's worth pointing out though that getting into this habit can potentially lead to issues. As pointed out in a comment below, this "pollutes" every element in the DOM. So it's best to be careful with this approach.

CodePudding user response:

You asked to add a function as a property of an element. That's an example:

function myFunc(){
    console.log(this);
}

element.myFunc = myFunc;
element.myFunc();
  • Related