I am trying to attach shadow dom to this but it does not attach and gives a error DOMExpection operation is not supported but when inherit from HTMLElement or HTMLSpanElement it works! So question is can i attach shadow dom to this when inherit from HTMLButtonElement if yes then how else not why! here is my code :-
class Home_Button extends HTMLButtonElement {
constructor() {
super();
this._dom = this.attachShadow({ mode: "open" });
this.createButton();
}
createButton() {
this.classList.add("contents");
const style = document.createElement("style");
style.textContent = `
.sentToHome{
margin: 1%;
padding: 1%;
border-radius: 5px;
border: 1px solid black;
}
.homeLink{
text-decoration: none;
color: green;
}
`;
const anchor = document.createElement("a");
anchor.innerText = "<< Home";
anchor.setAttribute("href", "/");
anchor.setAttribute("class", "homeLink");
const button = document.createElement("button");
button.setAttribute("class", "sentToHome");
button.appendChild(anchor);
this._dom.append(style, button);
}
}
customElements.define("simple-btn", Home_Button, { extends: "button" });
const sentToHomeBtn = new Home_Button();
document.body.appendChild(sentToHomeBtn);
CodePudding user response:
This will never work in Safari, because Apple has, since 2016, stated they will never implement Customized Built-In Elements, they have only implemented extends HTMLElement
Trigger createButton
from the connectedCallback
; you can't do DOM operations in the constructor
(besides shadowDOM content) because the element (this
) doesn't exist in the DOM yet.
Also note this._dom
isn't required, you get this.shadowRoot
for free from attachShadow()
To be clear this.classList
is the problem
CodePudding user response:
Well, @danny-365csi-engelman is also right but I found this answer.
According to the answer we can attach shadow dom on few elements and button does not exits in those elements.
I just inherit from HTMLElement class instead of HTMLButtonElement class. After that everything works fine!.
If you want to check current source code go here.