3

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me. In my question, I forgot to mention that I have the getCookie() function defined in another part of my code, so I changed that part back to what I originally had, but changing the customElements.define to the bottom worked. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.