Search code examples
javascripthtmlelementweb-component

How to create a custom HTML element using javascript?


I would like to be able to create a custom HTML element that can display the value of a cookie so that I can easily insert cookie values into my document. my code so far is:

var cNum = 0;

customElements.define('get-cookie', getC);

class getC extends HTMLElement {
  constructor() {
    super();

    cNum++;
    var cName = this.getAttribute('cName');
    this.setAttribute('id', cName + cNum);
    var currentE = document.getElementById(cName + cNum);
    var cValue = 'Oops! We have run into a problem';
    if (this.hasAttribute('cName')) {
      cValue = getCookie(this.getAttribute('img'));
    }
    var outC = document.createElement('a');
    outC.innerHTML = cValue;
    currentE.appendChild(outC);
  }
}

and

<p>
  Current User: <get-cookie cName="currentUSR" ></get-cookie>
</p>

But I get this error when I run it on firefox:

ReferenceError: can't access lexical declaration `getC' before initialization (myfile.js:4:1)

ALSO: I have zero jQuery knowledge, and would prefer if I could stay away from that.

All help is greatly appreciated! Thanks!

EDIT: I forgot to add that I already have the getCookie() function defined elsewhere in my code.


Solution

  • customElements.define('get-cookie', getC); should be at the bottom, after you've actually defined the class.

    Keeping it after the class definition should fix it:

    var cNum = 0;
    
    class getC extends HTMLElement {
      constructor() {
        super();
    
        cNum++;
        var cName = this.getAttribute('cName');
        this.setAttribute('id', cName + cNum);
        var currentE = document.getElementById(cName + cNum);
        var cValue = 'Oops! We have run into a problem';
        if (this.hasAttribute('cName')) {
          cValue = this.getCookie(this.getAttribute('img'));
        }
        var outC = document.createElement('a');
        outC.innerHTML = cValue;
        currentE.appendChild(outC);
      }
    
      getCookie() {
        return 'John Doe';
      }
    }
    
    customElements.define('get-cookie', getC);
    <p>Current User:
      <get-cookie cName="currentUSR"></get-cookie>
    </p>

    I was also not sure what getCookie is, here. So I created a method named getCookie on the class and now I'm using it in the constructor with the this keyword.