Need to put a heading, buttons, or other markup inside an element? innerHTML is a DOM property for getting or setting the HTML markup contained within it. A custom element inherits it from HTMLElement, so its class can set content with this.innerHTML. section 2.4
Start with a slider
Inside a slider’s connectedCallback, `this.innerHTML = '<div class="bg-overlay"></div><div class="thumb"></div>';` creates the background and thumb. The component can then find those elements with this.querySelector and style them. A short string works for this demo, though longer markup becomes harder to read. section 2.4
For a photo carousel, the same property supplies a heading, author line, image container, and navigation buttons. Attribute values fill the heading and author line; afterward, the component selects the new elements to show a photo and attach click listeners. The empty image container exists in the DOM even before styling makes it visible. section 2.6
Where should that assignment go? Use connectedCallback when populating a custom element visually. Moving the innerHTML assignment into its constructor can fail when the element is created: the resulting custom element is not allowed to have children. An attribute used to populate the markup may also still be unavailable there. section 4.2
Listing 7.7. Simplified business card example using templates to drive HTML and CSS
export default class BizCard extends HTMLElement {
static get observedAttributes() { return ['layout']; }
attributeChangedCallback( #1
name, oldvalue, newvalue) {
this.innerHTML = '';
const template = document.getElementById(newvalue);
const clone = template.content.cloneNode(true);
this.appendChild(clone);
}
}
if (!customElements.get('biz-card')) {
customElements.define('biz-card', BizCard);
}
Clearing innerHTML is also a simple way to replace a layout. Here, a layout-attribute change empties the component, clones the selected HTML template, and appends it. Anything kept inside the component would be cleared too, so the layout menu stays outside it. section 7.3
Setting innerHTML does not, by itself, protect a component’s contents. Outside code can select an exposed descendant and change its innerHTML; a broad page-level query can also accidentally select a button inside the component. section 8.1

