• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

85
Views
Unattached web component cannot call class methods if created before definition

Looks like if a custom element is created before it's been defined, it will have the HTMLElement constructor, and retain this even after the definition is completed.

Creating that element again will have the correct constructor, see code example below.

const comp = document.createElement("my-comp");

console.log('First element before definition: ', comp.constructor.name);

customElements.define("my-comp", class MyComp extends HTMLElement {
    constructor() { super(); }
    myMethod() { return; }
  }
);

console.log('First element after definition: ', comp.constructor.name);

try { comp.myMethod() }
catch (e) { console.error(e) }

const secondComp = document.createElement("my-comp");
console.log('Second element: ', secondComp.constructor.name);

about 3 years ago · Santiago Gelvez
1 answers
Answer question

0

If you are sure you have now defined the component, you can use !customElements.get(comp) && customElements.upgrade(comp) to upgrade the component so that its constructor is changed to the custom element's class.

const comp = document.createElement("my-comp");

console.log('Component before definition: ', comp.constructor.name);

customElements.define("my-comp", class MyComp extends HTMLElement {
    constructor() { super(); }
    myMethod() { return; }
  }
);

console.log('Component after definition: ', comp.constructor.name);

!customElements.get(comp) && customElements.upgrade(comp)

console.log('Component after upgrade: ', comp.constructor.name);

about 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error