Skip to content

Commit

Permalink
#792@minor: Adds support for adjacent sibling CSS query selector and …
Browse files Browse the repository at this point in the history
…improves the way query selection work.
  • Loading branch information
capricorn86 committed Apr 25, 2023
1 parent 1a827e3 commit 1b85259
Show file tree
Hide file tree
Showing 7 changed files with 327 additions and 192 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ export default class CSSStyleDeclarationElementStyle {
}
} else {
for (const element of options.elements) {
const matchResult = QuerySelector.match(element.element, selectorText);
const matchResult = QuerySelector.match(<IElement>element.element, selectorText);
if (matchResult.matches) {
element.cssTexts.push({
cssText: (<CSSStyleRule>rule)._cssText,
Expand Down
18 changes: 2 additions & 16 deletions packages/happy-dom/src/nodes/element/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -733,30 +733,16 @@ export default class Element extends Node implements IElement {
* @returns Closest matching element.
*/
public closest(selector: string): IElement {
let rootElement: IElement = this.ownerDocument.documentElement;
if (!this.isConnected) {
rootElement = this;
while (rootElement.parentNode) {
rootElement = <IElement>rootElement.parentNode;
}
}
const elements = rootElement.querySelectorAll(selector);

// eslint-disable-next-line
let parent: IElement = this;

while (parent) {
if (elements.includes(parent)) {
if (QuerySelector.match(parent, selector).matches) {
return parent;
}
parent = parent.parentElement;
}

// QuerySelectorAll() will not match the element it is looking in when searched for
// Therefore we need to check if it matches the root
if (rootElement.matches(selector)) {
return rootElement;
}

return null;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/src/nodes/node/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export default class Node extends EventTarget implements INode {
*/
public get parentElement(): IElement {
let parent = this.parentNode;
while (parent && parent.nodeType !== Node.ELEMENT_NODE) {
while (parent && parent.nodeType !== NodeTypeEnum.elementNode) {
parent = parent.parentNode;
}
return <IElement>parent;
Expand Down

0 comments on commit 1b85259

Please sign in to comment.