diff --git a/packages/happy-dom/src/query-selector/QuerySelector.ts b/packages/happy-dom/src/query-selector/QuerySelector.ts index ad0958c60..b0c702022 100644 --- a/packages/happy-dom/src/query-selector/QuerySelector.ts +++ b/packages/happy-dom/src/query-selector/QuerySelector.ts @@ -104,15 +104,15 @@ export default class QuerySelector { } const selector = new SelectorItem(selectorParts[0]); - const result = selector.match(currentNode); + const result = selector.match(currentNode); - if ((targetNode === currentNode || !currentNode.parentNode) && !result.matches) { + if ((targetNode === currentNode || !currentNode.parentElement) && !result.matches) { return { priorityWeight: 0, matches: false }; } return this.matchesSelector( - isDirectChild ? currentNode.parentNode : targetNode, - currentNode.parentNode, + isDirectChild ? currentNode.parentElement : targetNode, + currentNode.parentElement, result.matches ? selectorParts.slice(1) : selectorParts, priorityWeight + result.priorityWeight ); diff --git a/packages/happy-dom/test/nodes/element/Element.test.ts b/packages/happy-dom/test/nodes/element/Element.test.ts index 3d0489872..0d6b551a7 100644 --- a/packages/happy-dom/test/nodes/element/Element.test.ts +++ b/packages/happy-dom/test/nodes/element/Element.test.ts @@ -698,6 +698,7 @@ describe('Element', () => { it('Checks if the element matches with a descendant combinator', () => { const grandparentElement = document.createElement('div'); grandparentElement.setAttribute('role', 'alert'); + document.appendChild(grandparentElement); const parentElement = document.createElement('div'); parentElement.setAttribute('role', 'status'); @@ -709,6 +710,7 @@ describe('Element', () => { expect(element.matches('div[role="alert"] div.active')).toBe(true); expect(element.matches('div[role="article"] div.active')).toBe(false); + expect(element.matches('.nonexistent-class div.active')).toBe(false); }); it('Checks if the element matches with a child combinator', () => { diff --git a/packages/happy-dom/test/nodes/node/Node.test.ts b/packages/happy-dom/test/nodes/node/Node.test.ts index 53ed11f1e..57c7a5173 100644 --- a/packages/happy-dom/test/nodes/node/Node.test.ts +++ b/packages/happy-dom/test/nodes/node/Node.test.ts @@ -196,6 +196,14 @@ describe('Node', () => { expect(text.parentElement).toBe(null); }); + + it('Returns null if parent node is not an element.', () => { + const htmlElement = document.createElement('html'); + document.appendChild(htmlElement); + + expect(htmlElement.parentNode).toBe(document); + expect(htmlElement.parentElement).toBe(null); + }); }); describe('get baseURI()', () => {