0

Im trying to create a search bar type filter within shadow dom as follows

const root =  mainContainer.attachShadow({ mode: "open" });

      var filter = root.getElementById("myInput"), // search box
          list = root.querySelectorAll(".clubguests-card"); // all list items
          
     
      // (B) ATTACH KEY UP LISTENER TO SEARCH BOX
      filter.onkeyup = () => {
        // (B1) GET CURRENT SEARCH TERM
        let search = filter.value.toLowerCase();
     
        // (B2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
        for (let i of list) {
        
          let item = i.className.toLowerCase();
          console.log(item);
          if (item.indexOf(search) == -1) { i.classList.add("hide"); }
          else { i.classList.remove("hide"); }
        }
    }

The console is showing that the classes are added/removed, but the display is not affected.

If I use document.querySelectorAll(".clubguests-card") it works fine.

IS there a way of making this work within the shadow dom?

2 Answers2

1

Because shadow dom elements are isolated from outside styling.

You can link a stylesheet or use the visbility property to show/hide your shadow elements.

Note that inherited properties can go through the shadow boundary.

Alois Christen
  • 543
  • 3
  • 14
1

You can use the :host selector to access classes (and attributes) on the host/custom element;
then use CSS properties inside the component to set detailed styling

<my-component></my-component>
<my-component class="hide"></my-component>
<my-component class="show"></my-component>

<script>
customElements.define("my-component",class extends HTMLElement{
  constructor(){
    super()
      .attachShadow({mode:"open"})
      .innerHTML = `
        <style>
          :host(.hide){
            /* display:none; */
            --bgcolor:red;
          }
          :host(.show){
            --bgcolor:green;
          }
          h1{
            background: var(--bgcolor,grey);
          }
        </style>
        <h1>Hello Web Component!</h1>`
  }

})
</script>

Had you included a StackOverflow snippet in your question, I could have applied it to your source code.

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49