Advertisements
I have planned to get a rid of jQuery, just to learn more plain javascript to build my own libraries. I have created function __ similar to jQuery’s $.
First prototype method I choose to be _addClass which actually add a class to DOM element(s);
Html code is simple:
(() => {
function __(arg) {
if (!(this instanceof __))
return new __(arg);
this.element = null;
this.elements = null;
this.singleElement = false;
switch (arg.substring(0, 1)) {
case ".":
this.elements = document.getElementsByClassName(arg.substring(1));
break;
case "#":
this.element = document.getElementById(arg.substring(1));
this.singleElement = true;
break;
case "&":
this.elements = document.getElementsByName(arg.substring(1));
break;
default:
this.elements = document.querySelectorAll(arg);
break;
}
return this;
}
__.prototype._addClass = (a) => {
if (this.singleElement) {
this.element.classList.add(a);
return this.element;
} else {
this.elements.forEach((element) => element.classList.add(a));
return this.elements;
}
}
document.getElementById("btn").addEventListener("click", () => {
__("#test")._addClass("new-class-style");
})
})();
<div id="test">Div content</div>
<button id="btn">Button</button>
However, I’m getting error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘classList’)
pointing to this.element
or this.elements
or this.singleElement
are undefined and I just can’t figure why?
>Solution :
That’s because you’re using an arrow function for your _addClass
method and so the this
keyword becomes undefined
. Changing it back to normal function fixes the issue:
(() => {
function __(arg) {
if (!(this instanceof __)) return new __(arg);
this.element = null;
this.elements = null;
this.singleElement = false;
switch (arg.substring(0, 1)) {
case '.':
this.elements = document.getElementsByClassName(arg.substring(1));
break;
case '#':
this.element = document.getElementById(arg.substring(1));
this.singleElement = true;
break;
case '&':
this.elements = document.getElementsByName(arg.substring(1));
break;
default:
this.elements = document.querySelectorAll(arg);
break;
}
return this;
}
__.prototype._addClass = function (a) {
if (this.singleElement) {
this.element.classList.add(a);
return this.element;
} else {
this.elements.forEach((element) => element.classList.add(a));
return this.elements;
}
};
document.getElementById('btn').addEventListener('click', () => {
__('#test')._addClass('new-class-style');
});
})();
<div id="test">Div content</div>
<button id="btn">Button</button>