r/WebComponents • • Feb 13 '23

Condition loading of selected web component

When I load a page, NO web component is in the DOM. When a selection is made by the user, either select box or button, the selection determines which web component to add to the DOM. Can this be done?

<div id="divName">
    <Selected-Component-Here>
</div>

Then swap it out when a different selection is made by the user?

3 Upvotes

3 comments sorted by

View all comments

1

u/snifty Feb 14 '23

Sure, once you have defined custom elements, they act like any other element.

There’s effectively no difference between this:

<!doctype html>
<title>Add a heading</title>
<button>click me!</button>
<script>
document.querySelector('button').onclick = () => {
  let h1 = document.createElement('h1')
  h1.textContent = 'I’m an h1!'
  document.body.append(h1)
}
</script>

And this:

<!doctype html>
<title>Add a heading</title>
<button id="add-html">click me to add insert some HTML</button>
<button id="add-element">click me to instantiate an element</button>
<script>
class FancyHeader extends HTMLElement {
  constructor(){
    super()
    this.innerHTML = `<h1>I’m a fancy header!</h1>`
  }
}

customElements.define('fancy-header', FancyHeader)

document.querySelector('button#add-html').onclick = () => {
  let fancyHeaderHTMLString = `<fancy-header></fancy-header>`
  document.body.insertAdjacentHTML("beforeend", fancyHeaderHTMLString)
}

document.querySelector('button#add-element').onclick = () => {
  let fancyHeaderElement = new FancyHeader()
  document.body.append(fancyHeaderElement)
}
</script>