简体   繁体   中英

Is there a way to append html to web component?

I've a custom js web component:

class MainDiv extends HTMLElement {
  constructor() { super(); }
  connectedCallback() {
   this.innerHTML = '<div id="mydiv"><input type="text" oninput="onInput(event)"/></div>'
  }
}

and in main.js I've the function onInput*()

function onInput(event) {
  const mainDiv = document.getElementById("mydiv");
  const newLabel = document.createElement('span');
        newLabel.innerText = `${event.target.value.length}/255`; // output: 5/255...n/255
  mainDiv.appendChild(newLabel);
}

If I add a log in the onInput function it prints and does not return any error, but is not updating the webcomponent. Why?

There must be something else at play, your code works:

 <script> function onInput(event) { const mainDiv = document.getElementById("mydiv"); const newLabel = document.createElement('div'); newLabel.innerText = `${event.target.value.length}/255`; // output: 5/255...n/255 mainDiv.appendChild(newLabel); } customElements.define("my-element", class extends HTMLElement { connectedCallback() { this.innerHTML = '<div id="mydiv"><input type="text" oninput="onInput(event)"/></div>' } }); </script> <my-element></my-element>

Note

 constructor() {
   super();
 }

Is not required, it says run the constructor from my parent , which is also done when you leave out the constructor in your Component.
Only when you do more in the constructor is it required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM