Skip to content

Commit eb4b243

Browse files
committed
fix: generate valid selectors for children of shadow DOM
1 parent 3d70902 commit eb4b243

3 files changed

Lines changed: 20 additions & 11 deletions

File tree

src/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,11 @@ export function* cssSelectorGenerator(
5858
}
5959
}
6060

61-
yield getFallbackSelector(elements, options.useScope ? root : undefined);
61+
const rootWasProvided = custom_options.root !== undefined;
62+
yield getFallbackSelector(
63+
elements,
64+
options.useScope || rootWasProvided ? root : undefined,
65+
);
6266
}
6367

6468
export default getCssSelector;

src/selector-fallback.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,25 @@ export function getElementFallbackSelector(
1414
root?: ParentNode,
1515
): CssSelector {
1616
const parentElements = getElementParents(element, root).reverse();
17-
const elementsData = parentElements.map((element) => {
17+
const isShadowRoot = root instanceof ShadowRoot;
18+
19+
const elementsData = parentElements.map((element, index) => {
1820
const elementData = createElementData(
1921
element,
2022
[CSS_SELECTOR_TYPE.nthchild],
21-
OPERATOR.CHILD,
23+
// do not use child combinator for the first element in ShadowRoot
24+
isShadowRoot && index === 0 ? OPERATOR.NONE : OPERATOR.CHILD,
2225
);
2326
(elementData.selectors.nthchild ?? []).forEach((selectorData) => {
2427
selectorData.include = true;
2528
});
2629
return elementData;
2730
});
2831

29-
return [
30-
root ? ":scope" : ":root",
31-
...elementsData.map(constructElementSelector),
32-
].join("");
32+
// Don't use :scope prefix for ShadowRoot since it doesn't work correctly
33+
const prefix = isShadowRoot ? "" : root ? ":scope" : ":root";
34+
35+
return [prefix, ...elementsData.map(constructElementSelector)].join("");
3336
}
3437

3538
/**

src/utilities-dom.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,12 @@ export function getElementParents(
4343
): Element[] {
4444
root = root ?? getRootNode(element);
4545
const result = [];
46-
let parent: Element | null = element;
47-
while (isElement(parent) && parent !== root) {
48-
result.push(parent);
49-
parent = parent.parentElement;
46+
let parent: Node | null = element;
47+
while (parent && parent !== root) {
48+
if (isElement(parent)) {
49+
result.push(parent);
50+
}
51+
parent = parent.parentNode;
5052
}
5153
return result;
5254
}

0 commit comments

Comments
 (0)