0

I want to reimplement the jQuery functions.

For example .attr().

I found some threads like this.

So I tried something like:

HTMLElement.prototype.attr = (pAttributeName, pAttributeValue) => {
  if(pAttributeValue){
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
      return this.getAttribute(pAttributeName);
  }
};

But it don't work. Do I have to init the Elements first, in a constructor?

ru4ert
  • 998
  • 2
  • 14
  • 25

1 Answers1

2

From the documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value

In your case, this was bound to window object.

Using regular function

HTMLElement.prototype.attr = function(pAttributeName, pAttributeValue) {
  if (pAttributeValue) {
    this.setAttribute(pAttributeName, pAttributeValue);
  } else {
    return this.getAttribute(pAttributeName);
  }
};

document.querySelector('h1').attr('id', 'head')
#head {
  color: red;
}
<h1>Heading</h1>
User863
  • 19,346
  • 2
  • 17
  • 41