From 66c73d449a4e800bfedd7284f175e79165c5c19f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= <188768+fb55@users.noreply.github.com> Date: Fri, 20 Aug 2021 10:57:17 +0100 Subject: [PATCH] refactor(traversing): Only return elements in `closest` Makes the docs match the implementation and is in line with jQuery. Fixes #2056 --- src/api/traversing.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/api/traversing.ts b/src/api/traversing.ts index cec6f41412..7e6eac9f7a 100644 --- a/src/api/traversing.ts +++ b/src/api/traversing.ts @@ -293,7 +293,7 @@ export const parentsUntil = _matchUntil( */ export function closest( this: Cheerio, - selector?: AcceptedFilters + selector?: AcceptedFilters ): Cheerio { const set: Node[] = []; @@ -301,15 +301,21 @@ export function closest( return this._make(set); } + const selectOpts = { + xmlMode: this.options.xmlMode, + root: this._root?.[0], + }; + + const selectFn = + typeof selector === 'string' + ? (elem: Element) => select.is(elem, selector, selectOpts) + : getFilterFn(selector); + domEach(this, (elem: Node | null) => { - while (elem && elem.type !== 'root') { - if ( - !selector || - filterArray([elem], selector, this.options.xmlMode, this._root?.[0]) - .length - ) { + while (elem && isTag(elem)) { + if (selectFn(elem, 0)) { // Do not add duplicate elements to the set - if (elem && !set.includes(elem)) { + if (!set.includes(elem)) { set.push(elem); } break;