Skip to content

Commit

Permalink
fix(traversing): Make closest be able to start from text nodes (#2811)
Browse files Browse the repository at this point in the history
Fixes #2810
  • Loading branch information
Qualtagh authored Dec 12, 2022
1 parent d4e6ae5 commit 97f3739
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/api/traversing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,12 @@ describe('$(...)', () => {
const result = $('.saladbar', food).closest('ul');
expect(result).toHaveLength(0);
});

it('(selector) : should find closest element for text nodes', () => {
const textNode = $('.apple', food).contents().first();
const result = textNode.closest('#food') as Cheerio<Element>;
expect(result[0].attribs).toHaveProperty('id', 'food');
});
});

describe('.each', () => {
Expand Down
3 changes: 3 additions & 0 deletions src/api/traversing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,9 @@ export function closest<T extends AnyNode>(
: getFilterFn(selector);

domEach(this, (elem: AnyNode | null) => {
if (elem && !isDocument(elem) && !isTag(elem)) {
elem = elem.parent;
}
while (elem && isTag(elem)) {
if (selectFn(elem, 0)) {
// Do not add duplicate elements to the set
Expand Down

0 comments on commit 97f3739

Please sign in to comment.