最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to define a more customElements for same Class - Stack Overflow

programmeradmin4浏览0评论

I jsut tried to define new Custom Elements.

// the class
class MyEl extends HTMLElement {
  constructor() {
    // mandatory super call to upgrade the current context
    super();
    // any other Class/DOM related procedure
    this.setAttribute('custom-attribute', 'value');
this.innerText = 'new element';
  }
}

// its mandatory definition
customElements.define('my-el', MyEl);

// the JS way to create a custom element
const newMe = new MyEl();


document.body.appendChild(newMe);

I jsut tried to define new Custom Elements.

// the class
class MyEl extends HTMLElement {
  constructor() {
    // mandatory super call to upgrade the current context
    super();
    // any other Class/DOM related procedure
    this.setAttribute('custom-attribute', 'value');
this.innerText = 'new element';
  }
}

// its mandatory definition
customElements.define('my-el', MyEl);

// the JS way to create a custom element
const newMe = new MyEl();


document.body.appendChild(newMe);

Defining a new element of the same class will cause an error:
"Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry':
this constructor has already been used with this registry"

But i want to define new elements for same class. Could you suggest a way to display multiple items from the same class (MyEl).
Thank in advance!

Share Improve this question edited Mar 7, 2017 at 14:28 Supersharp 31.3k11 gold badges102 silver badges147 bronze badges asked Feb 23, 2017 at 22:30 Dmitriy DoroninDmitriy Doronin 7881 gold badge7 silver badges13 bronze badges 1
  • I think you're going to have trouble setting an attribute in the constructor. Attributes cannot be imposed by the element, they can only e from the HTML during construction, or via .setAttribute() after construction. – stephband Commented Apr 14, 2021 at 2:33
Add a ment  | 

2 Answers 2

Reset to default 4

Just try with an anonymous constructor and extend your MyEl:

class MyEl extends HTMLElement {
  // your definitions
}

customElements.define("my-better-element", class extends MyEl { })
customElements.define("my-second-element", class extends MyEl { })

customElements.define('my-el', MyEl) must be called only once to tell the browser you have a new <my-el> tag (aka to define a custom element).

Then you can create multiple elements just by using new:

const newMe1 = new MyEl();
const newMe2 = new MyEl();

Or createElement():

const newMe1 = document.createElement( 'my-el' )
const newMe2 = document.createElement( 'my-el' )

Or, in the html code:

<my-el></my-el>
<my-el></my-el> 
发布评论

评论列表(0)

  1. 暂无评论