diff --git a/src/index.ts b/src/index.ts index f7bd969..a4a3a58 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,13 @@ -export function injectStyles( - shadowRootElement: HTMLElement, - insertBeforeSelector: string, - styles: string -) { +export function 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 (currentStyleTags.length - 1 === index && styleAlreadyAdded === false) { + + if (root !== null) { + const styleElements = root.querySelectorAll('style'); + + if (!Array.from(styleElements).some(el => el.innerHTML === styles)) { const newStyleTag = document.createElement('style'); newStyleTag.innerHTML = styles; root.insertBefore(newStyleTag, root.querySelector(insertBeforeSelector)); } - }); + } }