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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…