Skip to content Skip to sidebar Skip to footer

Cannot Access Attributes Of A Custom Element From Its Constructor

I'm trying to create a polyfill of sorts using the Custom Elements API for custom elements used by an in-game browser engine to display buttons and similar. However, I can't seem t

Solution 1:

You cannot access the element DOM tree with querySelector() and appendChild(), and attributes with getAttribute() and setAttribute() in the constructor().

It's because at the time constructor() is called the custom element has no content yet.

You should defer that in the connectedCallback() method and it will be fine.

From the specs:

The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods.

In general, work should be deferred to connectedCallback as much as possible

Solution 2:

Although I swear I've seen that spec once (the one @Supersharp mentioned), but nowadays:

  • inspection of the attributes is allowed (works for me on Chrome, Firefox and Safari), so getAttribute is OKAY
  • mutation of the attributes is, as expected, forbidden

Well, probably we indeed should read that 'gain' as specifically referring to mutation.

One could say - wait, but if element can't gain any attribute - obviously there is nothing to inspect. Well, the following snippet works for me (on any browser):

classAextendsHTMLElement {
  constructor() {
    super();
    console.log(this.getAttribute('data-some'));
  }
}

globalThis.customElements.define('x-a', A);

const e = document.createElement('x-a');
// console: nullconst t = document.createElement('div');
t.innerHTML = '<x-a data-some="test"></x-a>';
// console: test

CodePen

Post a Comment for "Cannot Access Attributes Of A Custom Element From Its Constructor"