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

#622@patch: Fix Element.matches failing when using non-matching desce… #625

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactored slightly to always verify parentElement is not null, making it pass null checks in case you ever turn on strictNullChecks.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that would be good to turn on 🙂

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