Search code examples
javascripthideshowshadow-dom

Hide and Show elements inside shadow dom


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?


Solution

  • 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.