Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

custom element - Failed to execute 'createElement' on 'Document': The result must not have children

I've been using custom elements v1 for a while now via a polyfill. Chrome 54 (the first version with a native v1 implementation) started throwing errors when initializing my elements:

DOMException: Failed to execute 'createElement' on 'Document': The result must not have children

The offending line is a simple:

let el = document.createElement('my-custom-element');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Chrome's native implementation appears to be enforcing specification requirements that the polyfill was not. According to the "Requirements for custom element constructors" section of the spec:

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

The element that I was attempting to create added children to itself in its constructor.

The solution was to follow the recommendations of the spec:

In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice.

That is, add children in the connected callback and use a flag to ensure the element is only initialized on first connection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...