Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(traversing): Only return elements in closest #2057

Merged
merged 1 commit into from
Aug 20, 2021
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