Skip to content

Commit 66c73d4

Browse files
committed
refactor(traversing): Only return elements in closest
Makes the docs match the implementation and is in line with jQuery. Fixes #2056
1 parent 57d1dcf commit 66c73d4

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/api/traversing.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -293,23 +293,29 @@ export const parentsUntil = _matchUntil(
293293
*/
294294
export function closest<T extends Node>(
295295
this: Cheerio<T>,
296-
selector?: AcceptedFilters<Node>
296+
selector?: AcceptedFilters<Element>
297297
): Cheerio<Node> {
298298
const set: Node[] = [];
299299

300300
if (!selector) {
301301
return this._make(set);
302302
}
303303

304+
const selectOpts = {
305+
xmlMode: this.options.xmlMode,
306+
root: this._root?.[0],
307+
};
308+
309+
const selectFn =
310+
typeof selector === 'string'
311+
? (elem: Element) => select.is(elem, selector, selectOpts)
312+
: getFilterFn(selector);
313+
304314
domEach(this, (elem: Node | null) => {
305-
while (elem && elem.type !== 'root') {
306-
if (
307-
!selector ||
308-
filterArray([elem], selector, this.options.xmlMode, this._root?.[0])
309-
.length
310-
) {
315+
while (elem && isTag(elem)) {
316+
if (selectFn(elem, 0)) {
311317
// Do not add duplicate elements to the set
312-
if (elem && !set.includes(elem)) {
318+
if (!set.includes(elem)) {
313319
set.push(elem);
314320
}
315321
break;

0 commit comments

Comments
 (0)