polyfills icon indicating copy to clipboard operation
polyfills copied to clipboard

[Custom Elements] Custom element not "recognized" when added with Element.outerHTML

Open dpobel opened this issue 8 years ago • 5 comments

This is happening with Firefox (not tested with others browsers that need this polyfill and of course in Chrome this works well) and with the 1.0.0-rc.1 version. So if you add a custom element with Element.outerHTML, the custom element seems to not be "recognized" (the constructor is not called).

I wrote a simple test page where you can see the bug: http://vrac.pwet.fr/customelement_outerhtml.html

dpobel avatar Mar 09 '17 10:03 dpobel

The fact is that technically the property outerHTML is available for writing. But the element does not change, but is replaced with a new one, which is immediately created from the new outerHTML.

In this case, the variable, in which the old element was originally, and in which we "overwrote" outerHTML, remains with the old element. This can easily lead to errors.

That's why I suggest never rewriting outerHTML.

web-padawan avatar Mar 09 '17 10:03 web-padawan

@web-padawan that's a very valid point :) I thought you were talking about compatibility across browsers.

On the bug it itself, here is the workaround I'm using:

// instead of
// element.outerHTML = htmlUpdate;
// htmlUpdate contains something like: <div><my-custom-element></my-custom-element></div>
const doc = new new DOMParser().parseFromString(htmlUpdate, "text/html");
element.parentNode.replaceChild(doc.body.firstChild, element); // even returns the new element

dpobel avatar Mar 09 '17 14:03 dpobel

Hi, @dpobel, outerHTML isn't patched at the moment, so the polyfill won't notice it and realize it needs to upgrade the new tree. If you want to submit a PR, the innerHTML patch is likely a good starting point. One thing to note is that the innerHTML patch is applied conditionally because it isn't in the correct place in some of the browsers we need to support; I bet that's also true for outerHTML.

Also, you're probably seeing this work in Chrome because the polyfill only kicks in if either customElements doesn't exist when it runs or you explicitly force it to run. Chrome currently ships custom elements in stable, so the native implementation is used there. (This will apply to Safari 10.1 as well.)

bicknellr avatar Mar 20 '17 22:03 bicknellr

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 24 '21 06:04 stale[bot]

This issue has been automatically closed after being marked stale. If you're still facing this problem with the above solution, please comment and we'll reopen!

stale[bot] avatar Apr 27 '25 05:04 stale[bot]