Cannot Access Attributes Of A Custom Element From Its Constructor
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
Post a Comment for "Cannot Access Attributes Of A Custom Element From Its Constructor"