Search code examples
javascripthtmlcssshadow-domshadow-root

Modify shadow root on css


I'm trying with a thousand different css rules, but I can't find any that do what I require. I have a desire to edit a custom element in my css file after it is placed in the dom, but I can't, how can I do? If there is already a question asked, I apologize and please link it to me

class GacInput extends HTMLElement {
  constructor() {
    super();
    this.root = this.attachShadow({
      mode: 'open'
    });
    this.root.innerHTML = `
      <style>
        :host {
          display: flex;
          width: min-content;
        }
        input {
          display: block;
        }
      </style>
      <label></label>
      <input type="text">
    `;
  }
  static get observedAttributes() {
    return ['label', 'align'];
  }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === 'label') {
      this.root.querySelector('label').innerText = newValue;
    }
    if (name === 'align') {
      switch (newValue) {
        case "right":
          this.root.host.style.flexDirection = "row-reverse";
          break;
        case "top":
          this.root.host.style.flexDirection = "column";
          break;
        case "bottom":
          this.root.host.style.flexDirection = "column-reverse";
          break;
        default:
          this.root.host.style.flexDirection = "row";
      }
    }
  }
}
customElements.define('gac-input', GacInput);
gac-input::shadow label {
  background-color: blue;
}

gac-input /deep/ label {
  background-color: blue;
}

 :host(gac-input) label {
  background-color: blue;
}
<gac-input label="nome" align="top"></gac-input>


Solution

  • Not sure if this will help with your specific case, But my go-to for editing a css-property after the DOM is loaded is using variables.

    For example:

    :root {
        --custom-color: #000000;
        --flex-direction: column;
    }
    
    .element {
        background-color: var(--custom-color);
        flex-direction: var(--flex-direction);
    }
    

    And to change it via javascript:

    const root = document.querySelector(':root');
    
    root.style.setAttribute('--custom-color', '#999999');