Skip to content

Commit

Permalink
Merge pull request #625 from IGx89/task/622-fix-matches-non-matching-…
Browse files Browse the repository at this point in the history
…descendant-selector

#622@patch: Fix Element.matches failing when using non-matching desce…
  • Loading branch information
capricorn86 committed Oct 18, 2022
2 parents a6407b7 + 4906155 commit 999cd31
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/happy-dom/src/query-selector/QuerySelector.ts
Expand Up @@ -106,7 +106,14 @@ export default class QuerySelector {
const selector = new SelectorItem(selectorParts[0]);
const result = selector.match(<IElement>currentNode);

if ((targetNode === currentNode || !currentNode.parentElement) && !result.matches) {
if (result.matches && selectorParts.length === 1) {
return {
priorityWeight: priorityWeight + result.priorityWeight,
matches: true
};
}

if (!currentNode.parentElement || (targetNode === currentNode && !result.matches)) {
return { priorityWeight: 0, matches: false };
}

Expand Down
14 changes: 14 additions & 0 deletions packages/happy-dom/test/nodes/element/Element.test.ts
Expand Up @@ -713,6 +713,19 @@ describe('Element', () => {
expect(element.matches('.nonexistent-class div.active')).toBe(false);
});

it('Checks if a detached element matches with a descendant combinator', () => {
const parentElement = document.createElement('div');
parentElement.setAttribute('role', 'status');

const element = document.createElement('div');
element.className = 'active';
parentElement.appendChild(element);

expect(element.matches('div[role="status"] div.active')).toBe(true);
expect(element.matches('div[role="article"] div.active')).toBe(false);
expect(parentElement.matches('.nonexistent-class div[role="status"]')).toBe(false);
});

it('Checks if the element matches with a child combinator', () => {
const grandparentElement = document.createElement('div');
grandparentElement.setAttribute('role', 'alert');
Expand All @@ -727,6 +740,7 @@ describe('Element', () => {

expect(element.matches('div[role="status"] > div.active')).toBe(true);
expect(element.matches('div[role="alert"] > div.active')).toBe(false);
expect(grandparentElement.matches('div > div[role="alert"]')).toBe(false);
});
});

Expand Down

0 comments on commit 999cd31

Please sign in to comment.