gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

Create your own native web component

box.css

box-element > div {
  color: #555;
  background: #00BCD4;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

box.js

class Box extends HTMLElement {
  constructor(text) {
    super()
    this.text = text
  }
  connectedCallback() {
    this.innerHTML = `<div>${this.text}</div>`
  }
}
customElements.define('box-element', Box)

index.html

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="box.css">
</head>
<body>
  <script src="box.js"></script>
  <script>
    const box = new Box(`I'm a box`)
    document.body.appendChild(box)
  </script>
</body>
</html>
View on GitHub Gist

Tags: web component