Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style not injected when no existing style element present in shadow DOM #4

Closed
cns-dan opened this issue Oct 3, 2019 · 1 comment
Closed

Comments

@cns-dan
Copy link

cns-dan commented Oct 3, 2019

  const root = shadowRootElement.shadowRoot;
  let styleAlreadyAdded = false;
  const currentStyleTags = Array.from(root.querySelectorAll('style'));
  currentStyleTags.forEach((element: HTMLStyleElement, index) => {
    if (element.innerHTML === styles) {
      styleAlreadyAdded = true;
    }
    if (currentStyleTags.length - 1 === index && styleAlreadyAdded === false) {
      const newStyleTag = document.createElement('style');
      newStyleTag.innerHTML = styles;
      root.insertBefore(newStyleTag, root.querySelector(insertBeforeSelector));
    }
  });

If there are no style elements already within the shadow DOM, currentStyleTags will be an empty array and the code path that conditionally injects the new styles never executes.

@ChristopherTotty
Copy link

A fix for this problem if anyone wants to run with it.

    public injectStyles(
        shadowRootElement: HTMLElement,
        insertBeforeSelector: string,
        styles: string
    ) {
        const root = shadowRootElement.shadowRoot;
        let styleAlreadyAdded = false;
        const currentStyleTags = Array.from(root.querySelectorAll('style'));
        currentStyleTags.forEach((element: HTMLStyleElement, index) => {
            if (element.innerHTML === styles) {
                styleAlreadyAdded = true;
            }
        });

        if (styleAlreadyAdded === false) {
            const newStyleTag = document.createElement('style');
            newStyleTag.innerHTML = styles;
            root.insertBefore(newStyleTag, root.querySelector(insertBeforeSelector));
        }
    }

@cns-dan cns-dan mentioned this issue Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants