Web Component with an Attribute

Uses attributes to set the resulting content

by Erik Gillespie

HTML

<radio-input name="fave-web-lang" value="html" label="HTML"></radio-input>
<radio-input name="fave-web-lang" value="css" label="CSS"></radio-input>
<radio-input name="fave-web-lang" value="js" label="JavaScript"></radio-input>

CSS

body {
  background-color: #222;
  color: white;
}

JavaScript

class RadioInput extends HTMLElement {
  constructor () {
    super()
    const name = this.getAttribute('name') || ''
    const value = this.getAttribute('value') || ''
    const label = this.getAttribute('label') || value
    const id = value.toLowerCase().replace(/\s+/g, '-')
    this.innerHTML = `
      <div>
        <input id="${id}" type="radio" name="${name}" value="${value}">
        <label for="${id}">${label}</label>
      </div>
    `
  }
}

customElements.define('radio-input', RadioInput)