home ~ projects ~ socials

Get The Value From A Custom Element's Attribute In A Web Component

HTML

<wc-example alfa="ping"></wc-example>
<wc-example></wc-example>

Output

JavaScript

customElements.define('wc-example', 
  class Alfa extends HTMLElement {
    constructor() {
        super()
        this.attachShadow({ mode: 'open' })
        this.content = document.createElement('div')
        this.shadowRoot.append(this.content)
    }

    loadAttributes() {
      const alfaAttrValue = this.hasAttribute('alfa')
        ? `Found alfa attribute with: ${this.getAttribute('alfa')}`
        : "no alfa attribute in the element"
      this.content.innerHTML = alfaAttrValue 
    }

    connectedCallback() {
      this.loadAttributes()
    }
  }
)
-- end of line --