In most cases, the problem will be that you are trying to create an element that will magically have attributes when it is first added to the DOM, which is not expected behaviour for HTML elements. Think about:
const div = document.createElement("div");
document.body.append(div);
For divs, and all other element types, you will never have a DOM element created that already has attributes like <div class="my-class"></div>
. Classes and all other attributes are always added after the element has been created with .createElement()
, like:
const div = document.createElement("div");
div.className = "my-class";
document.body.append(div);
.createElement()
will never create an element that already has attributes such as classes. The same applies for custom elements.
It would therefore be unexpected if:
const myElement = document.createElement("my-element");
document.body.append(myElement);
added a DOM element like <my-element class="unexpected-attribute"></my-element>
.
You shouldn't be adding attributes like classes to the actual custom element. If you want to add attributes and styling, you should attach children to your element (in a shadowRoot for a web component), for example a div to which you can add whatever attributes you want, whilst leaving your actual custom element free of attributes.
Example:
class SquareLetter extends HTMLElement {
constructor() {
super();
const div = document.createElement("div");
div.className = getRandomColor();
this.appendChild(div);
}
}
customElements.define("square-letter", SquareLetter);
As a web component:
class SquareLetter extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"});
const div = document.createElement("div");
div.className = getRandomColor();
this.shadowRoot.append(div);
}
}
customElements.define("square-letter", SquareLetter);