Estoy tratando de crear un elemento personalizado "cuadro de color" que necesitará un atributo llamado "color" para identificar el color del cuadro. Entonces, por ejemplo, <color-box color="green"></color-box> dará un cuadrado de 100 píxeles de ancho y 100 píxeles de alto, con el color de fondo verde. No tengo ningún problema al definir el elemento directamente con HTML haciendo <color-box color="red"></color-box> , todo va bien, pero en mi caso, necesito crear este elemento con solo javascript, así:
let colorBoxElement = document.createElement("color-box"); colorBoxElement.setAttribute("color", "red"); document.body.appendChild(colorBoxElement) Lo que sucede es que el constructor se ejecuta antes colorBoxElement.setAttribute("color", "red") y eso no es lo que quiero, porque estoy usando ese atributo en mi constructor. Quiero que el constructor se ejecute cuando todos sus atributos requeridos estén allí (en este caso, solo 1: color ) o cuando realmente se agregue al cuerpo del documento usando document.body.appendChild(colorBoxElement)
¿Hay alguna forma posible de hacer esto, o al menos hacer algo similar a lo que necesito? Aquí está mi código:
// Defining the custom element class ColorBox extends HTMLElement { constructor() { super() let shadow = this.attachShadow({mode: "open"}) let container = document.createElement("div") container.style.width = "100px" container.style.height = "100px" switch(this.getAttribute("color")) { case "red": container.style.backgroundColor = "red" break; case "green": container.style.backgroundColor = "green" break; default: throw new Error("Color attribute not valid: " + this.getAttribute("color")) } shadow.appendChild(container) } } customElements.define("color-box", ColorBox) // Creating the custom element let colorBoxElement = document.createElement("color-box") // This will get executed after the constructor was ran (problem) colorBoxElement.setAttribute("color", "green") // Appending the element to body document.body.appendChild(colorBoxElement) <body> <color-box color="red"></color-box> </body>