0

I want to make a function that instead of using a parameter, it will get the value before the dot like any JavaScript method works. This is what I have that works using a parameter...

var myElement = document.getElementsByTagName('DIV')[0];

setToBlack(myElement);

function setToBlack(element) {
    element.style.backgroundColor = 'black';
}

However I would like to do this were the element is passed without using any parameter and is declared before the dot. This example does not work and I am struggling to get it to work. Any advice will be most appreciated. I am sure this has been asked on stackoverflow before but I am unable to find it with searching since I am unsure of the proper definitions on what this is called.

var myElement = document.getElementsByTagName('DIV')[0];

myElement.setToBlack();

function setToBlack() {
    this.style.backgroundColor = 'black';
}
bhutto54
  • 7
  • 3
  • Well, `setToBlack` is not a method (function property) of the `myElement` object. You cannot access it through `myElement.setToBlack`, so you cannot invoke it as a method like that either. – Bergi Jul 10 '20 at 20:52
  • "*I am unsure of the proper definitions on what this is called*" - it's a method call, or method invocation. – Bergi Jul 10 '20 at 20:53
  • @Triby. I think this is what I am looking for. Are these called javascript methods instead of javascript functions? – bhutto54 Jul 10 '20 at 21:56
  • They are called methods because they belongs to an object (object, class, HTMLElement, etc.) and _normal functions_ doesn't. – Triby Jul 10 '20 at 21:58
  • Which should I use? Element.prototype... or HTMLElement.prototype... – bhutto54 Jul 10 '20 at 22:41

1 Answers1

1

You could write a wrapper class like this

OPTION 1

class ElementWrapper {
    constructor(element) {
      this.element = element;
    }
  
  setToBlack() {
    this.element.style.backgroundColor = 'black';
  }
  
}

// Use the wrapper class
const targetElement = document.getElementsByTagName('DIV')[0];
const wrappedElement = new ElementWrapper(targetElement);
wrappedElement.setToBlack();

OPTION 2

function setToBlack() {
    this.style.backgroundColor = 'black';
}

const element = document.getElementsByTagName('div')[0];
element.setToBlack = setToBlack;

element.setToBlack();
Grey
  • 489
  • 3
  • 7
  • Is there a way to the executing code simple just like `myElement.setToBlack();`? Which has the "clean" javascript syntax? I was planning on having the function in a seperate JS file and being able to call the function simply using `myElement.setToBlack();` in a different JS file. – bhutto54 Jul 10 '20 at 21:39
  • See my edited response. – Grey Jul 10 '20 at 23:10
  • @bhutto54 Kindly upvote and accept the answer. It will help your reputation as well. :) – Grey Jul 16 '20 at 10:36