Skip to content

Commit

Permalink
refactor(traversing): Only return elements in closest (#2057)
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 committed Aug 20, 2021
1 parent 57d1dcf commit f7226aa
Showing 1 changed file with 14 additions and 8 deletions.
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

0 comments on commit f7226aa

Please sign in to comment.