Let's assume I've defined a custom element like this:
class ArticleElement extends HTMLElement {
constructor() {
super();
console.log(this); //the node we are (re)defining
this.innerHTML = `
<article>
<h2>${this.getAttribute("title")}</h2>
<p>${this.innerHTML}</p>
</article>`;
}
}
customElements.define("custom-article", ArticleElement);
My question is - how does this
become the node we are (re)defining? Is this possible to be done in pure JavaScript without using native methods? Because if we execute the constructor with new
, this
points to the newly created object. I was trying to implement the define
method like this:
function define(tag, CustomElement) {
const elementsCollection = document.getElementsByTagName(tag);
Object.keys(elementsCollection).forEach((index) => {
Object.setPrototypeOf(elementsCollection[index], CustomElement.prototype);
elementsCollection[index].constructor();
});
}
define("custom-article", ArticleElement);
But then remembered that the constructor of a class cannot be executed without new.
Here's my html file (if it even matters):
...
<custom-article title="Today is the day!">
Today is a great day to go out and breathe some fresh air!
</custom-article>
...