Similar to jQuery .closest() but traversing descendants?

后端 未结 16 758
情书的邮戳
情书的邮戳 2020-12-07 15:13

Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is

16条回答
  •  甜味超标
    2020-12-07 15:59

    Pure JS solution (using ES6).

    export function closestDescendant(root, selector) {
      const elements = [root];
      let e;
      do { e = elements.shift(); } while (!e.matches(selector) && elements.push(...e.children));
      return e.matches(selector) ? e : null;
    }
    

    Example

    Considering the following structure:

    div                 == $0
    ├── div             == $1
    │   ├── div
    │   ├── div.findme  == $4
    │   ├── div
    │   └── div
    ├── div.findme      == $2
    │   ├── div
    │   └── div
    └── div             == $3
        ├── div
        ├── div
        └── div
    
    closestDescendant($0, '.findme') === $2;
    closestDescendant($1, '.findme') === $4;
    closestDescendant($2, '.findme') === $2;
    closestDescendant($3, '.findme') === null;
    

    function closestDescendant(root, selector) {
      const elements = [root];
      let e;
      do { e = elements.shift(); } while (!e.matches(selector) && elements.push(...e.children));
      return e.matches(selector) ? e : null;
    }
    
    const [$0, $1, $2, $3, $4] = [0, 1, 2, 3, 4].map(x => document.querySelector(`#e${x}`));
    
    console.log(closestDescendant($0, '.findme')); // $2
    console.log(closestDescendant($1, '.findme')); // $4
    console.log(closestDescendant($2, '.findme')); // $2
    console.log(closestDescendant($3, '.findme')); // null

提交回复
热议问题