DasSaffe
DasSaffe

Reputation: 2198

custom HTML tags and attributes

I'm really kind of struggling at the moment and I don't know how hard it can possibly be. I followed several different tutorials and answers here on SO and YouTube, but all are doing it differently and I am kind of stuck right now.

All I want is a custom HTML-Tag with some custom attributes

I tried it with this approach (JS)

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

    var rarity = this.getAttribute("rarity");
    console.log("rarity: " + rarity);
    }
}

customElements.define("my-trophy", MyTrophy);

HTML

<body>
    <my-trophy rarity="silver" id="someID">lorem ipsum</my-trophy>
</body>

The JS-File is loaded in the header of the HTML-File

Since it is not an object as well, I cannot log the my-trophy tag as well. It is planned, that I have multiple tags of these kind in my final dom.

It doesn't matter what I try, I don't get the rarity-attribute to work. Am I supposed to just use data-attributes for that case, even though this here is a custom HTML tag?

References:

Some of the methods simply don't work (anymore?) (for example, it seems like registerElement isn't available anymore, but there is defineElement now).

I would expect, if I log console.log(rarity), that the output would be "silver".

For the completness of the question: I'm trying to run the script in Google Chrome

Thanks for any help

Upvotes: 4

Views: 1041

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

I ran your code and it worked just fine with the constructor, but you could try connectedCallback instead. This method gets called any time an element is added to the document.

Make sure your script runs in the <head> of the document, before your <body> is executed. HTML/scripts run top-to-bottom. Your element needs to be registered before it is rendered.

Update: Please refer to the "Custom elements" - JavaScript.info article that was linked by Martin Braun for a better understanding. The official MDN documentation can be viewed here: "Using custom elements" - MDN.

class MyTrophy extends HTMLElement {
  connectedCallback() {
    const rarity = this.getAttribute('rarity');
    console.log(`Rarity: ${rarity}`);
  }
}

customElements.define('my-trophy', MyTrophy);
my-trophy {
  font-size: 3em;
}

my-trophy[rarity="silver"] {
  color: #777;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<my-trophy class="fas fa-trophy" rarity="silver"></my-trophy>

Upvotes: 7

Related Questions