Skip to content

Commit

Permalink
Merge pull request #615 from IGx89/task/614-fix-descendant-combinators
Browse files Browse the repository at this point in the history
#614@patch: Element.matches not working properly with descendant combinators.
  • Loading branch information
capricorn86 committed Oct 12, 2022
2 parents bda8b83 + de53a51 commit 3ee3996
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/happy-dom/src/query-selector/QuerySelector.ts
Expand Up @@ -106,14 +106,14 @@ export default class QuerySelector {
const selector = new SelectorItem(selectorParts[0]);
const result = selector.match(<Element>currentNode);

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

return this.matchesSelector(
isDirectChild ? currentNode.parentNode : targetNode,
currentNode.parentNode,
selectorParts.slice(1),
result.matches ? selectorParts.slice(1) : selectorParts,
priorityWeight + result.priorityWeight
);
}
Expand Down
32 changes: 32 additions & 0 deletions packages/happy-dom/test/nodes/element/Element.test.ts
Expand Up @@ -694,6 +694,38 @@ describe('Element', () => {

expect(element.matches('.container, .active')).toBe(true);
});

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

const parentElement = document.createElement('div');
parentElement.setAttribute('role', 'status');
grandparentElement.appendChild(parentElement);

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

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

it('Checks if the element matches with a child combinator', () => {
const grandparentElement = document.createElement('div');
grandparentElement.setAttribute('role', 'alert');

const parentElement = document.createElement('div');
grandparentElement.setAttribute('role', 'status');
grandparentElement.appendChild(parentElement);

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="alert"] > div.active')).toBe(false);
});
});

describe('closest()', () => {
Expand Down

0 comments on commit 3ee3996

Please sign in to comment.