I'm trying to use some custom elements in my website, and in firefox it works great so far. In google chrome however, it just fails silently - the constructor of my custom element is never called, and it also doesn't throw an error.
Suppose this minimal example:
<!DOCTYPE html>
<html>
<head>
<script>
class MyElement extends HTMLDivElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element",MyElement,{extends:"div"});
console.log("Added MyElement to custom element registry!");
}
</script>
</head>
<body onload="addCustomElement()">
<my-element style="display:block;width:100px;height:100px;background:#ff0000"></my-element>
</body>
</html>
I would expect this to create a custom element class MyElement
and convert all my-element
-elements in the DOM into instances of that class once added to the custom element registry, turning the originally red component green. In firefox, this is exactly what happens, but in google chrome, it stays red. The console indicates that the element was added to the registry, but its constructor was never called.
Am I missing something? Is this a problem with chrome, or am I doing something wrong? And how can I get it to work there?
Working example here
class MyElement extends HTMLElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element", MyElement)
console.log("Added MyElement to custom element registry!");
}
// add call here, because onload did not work for me
addCustomElement()
https://jsfiddle.net/so98Lauz/1/
changes:
addCustomElement
function in js to be sure that is executed{extends:"div"}
from customElements.define