How do I append a Web Component created programmatically?

浪子不回头ぞ 提交于 2020-03-23 07:37:09

问题


I created a Web Component class to extend div, and used customElements.define() to define it:

class Resize_Div extends HTMLDivElement {
  constructor(){
      super();
      this.cpos = [0,0];
      <etc.>
  }
  connectedCallback() {
    console.log( 'connected' );
  }
  <etc.>
}

customElements.define('resize-div', Resize_Div, { extends:'div'} );

If I test in html, as <div is:'resize-div'> </div>, it works fine.

Now I want to use createElement to create an instance programmatically, using the options to declare the is, as documented here:

let dv = document.createElement('ul', { is: 'resize-div' })

The browser developer tools show it created, with outerHTML as below:

outerHTML: "<div is="resize-div"></div>"

As documented, "The new element [has] an is attribute whose value is the custom element's tag name."

Now I set id, class, and style, and attach the new element to the DOM via:

document.getElementById( parent ).appendChild( dv );

Now look at it again: the is attribute is stripped off and it doesn't function as a Web Component:

attributes: NamedNodeMap
0: id
1: class
2: style
length: 3

The docs for the deprecated registerElement here show an example using document.body.appendChild( new myTag() ), but that's obsolete.

So what is the correct way to create a Web Component programmatically and attach it to a document?

(ps. I'm working on Chromium Version 70.0.3538.67 (Official Build) Built on Ubuntu, running on Ubuntu 16.04 (64-bit)


回答1:


You've defined an extended <div> but you try to create a <ul> element.

If you create a <div> instead it will work:

let dv = document.createElement('div', { is: 'resize-div' })

The new syntax also works:

document.body.appendChild( new Resize_Div )

NB: When you create an customized built-in element programmatically the is attribute is not added in the HTML code but it still acts as a custom element, and outerHTML will return the HTML with is correctly populated as explained in the specs.



来源:https://stackoverflow.com/questions/54718081/how-do-i-append-a-web-component-created-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!