Skip to content

Commit ee58f8b

Browse files
committed
fix: allow passing non-element nodes to getClosestElement
1 parent 6ba3d66 commit ee58f8b

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

packages/component-base/src/dom-utils.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export function getClosestElement(selector, node) {
7474
return null;
7575
}
7676

77-
return node.closest(selector) || getClosestElement(selector, node.getRootNode().host);
77+
return node.closest?.(selector) || getClosestElement(selector, node.getRootNode().host);
7878
}
7979

8080
/**

packages/component-base/test/dom-utils.test.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ describe('dom-utils', () => {
4545
});
4646

4747
describe('getClosestElement', () => {
48-
let element;
48+
let element, node;
4949

5050
const tag = defineCE(
5151
class ShadowElement extends HTMLElement {
@@ -65,26 +65,30 @@ describe('dom-utils', () => {
6565

6666
it('should return the closest element matching the selector within the shadow root', () => {
6767
element = fixtureSync(`<${tag}></${tag}>`);
68-
const node = element.shadowRoot.querySelector('.child');
68+
node = element.shadowRoot.querySelector('.child');
6969
const expected = element.shadowRoot.querySelector('.parent-2');
7070
expect(getClosestElement('.parent', node)).to.equal(expected);
7171
});
7272

7373
it('should return the closest element matching the selector across the shadow root', () => {
7474
element = fixtureSync(`<div class="wrapper"><${tag}></${tag}></div>`);
75-
const node = element.querySelector(tag).shadowRoot.querySelector('.parent');
75+
76+
node = element.querySelector(tag).shadowRoot;
77+
expect(getClosestElement('.wrapper', node)).to.equal(element);
78+
79+
node = element.querySelector(tag).shadowRoot.querySelector('.parent');
7680
expect(getClosestElement('.wrapper', node)).to.equal(element);
7781
});
7882

7983
it('should return null when no closest element is found', () => {
8084
element = fixtureSync(`<${tag}></${tag}>`);
81-
const node = element.shadowRoot.querySelector('.child');
85+
node = element.shadowRoot.querySelector('.child');
8286
expect(getClosestElement('.not-existing-class', node)).to.be.null;
8387
});
8488

8589
it('should return the passed element if it matches the selector', () => {
8690
element = fixtureSync(`<${tag}></${tag}>`);
87-
const node = element.shadowRoot.querySelector('.child');
91+
node = element.shadowRoot.querySelector('.child');
8892
expect(getClosestElement('.child', node)).to.equal(node);
8993
});
9094
});

0 commit comments

Comments
 (0)