Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/api/traversing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,23 +293,29 @@ export const parentsUntil = _matchUntil(
*/
export function closest<T extends Node>(
this: Cheerio<T>,
selector?: AcceptedFilters<Node>
selector?: AcceptedFilters<Element>
): Cheerio<Node> {
const set: Node[] = [];

if (!selector) {
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;
Expand Down