From 3820a66ab134c341bedf0ea61d1b612e6d04fb5b Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 22 Apr 2021 08:45:39 +0300 Subject: [PATCH] Add DOM find snippets --- snippets/findClosestAnchor.md | 22 ++++++++++++++++++++++ snippets/findClosestMatchingNode.md | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 snippets/findClosestAnchor.md create mode 100644 snippets/findClosestMatchingNode.md diff --git a/snippets/findClosestAnchor.md b/snippets/findClosestAnchor.md new file mode 100644 index 000000000..1083b3520 --- /dev/null +++ b/snippets/findClosestAnchor.md @@ -0,0 +1,22 @@ +--- +title: findClosestAnchor +tags: browser,intermediate +--- + +Finds the anchor node closest to the given `node`, if any. + +- Use a `for` loop and `Node.parentNode` to traverse the node tree upwards from the given `node`. +- Use `Node.nodeName` and `String.prototype.toLowerCase()` to check if any given node is an anchor (`'a'`). +- If no matching node is found, return `null`. + +```js +const findClosestAnchor = node => { + for (let n = node; n.parentNode; n = n.parentNode) + if (n.nodeName.toLowerCase() === 'a') return n; + return null; +}; +``` + +```js +findClosestAnchor(document.querySelector('a > span')); // a +``` diff --git a/snippets/findClosestMatchingNode.md b/snippets/findClosestMatchingNode.md new file mode 100644 index 000000000..8c0c200de --- /dev/null +++ b/snippets/findClosestMatchingNode.md @@ -0,0 +1,22 @@ +--- +title: findClosestMatchingNode +tags: browser,intermediate +--- + +Finds the closest matching node starting at the given `node`. + +- Use a `for` loop and `Node.parentNode` to traverse the node tree upwards from the given `node`. +- Use `Element.matches()` to check if any given element node matches the provided `selector`. +- If no matching node is found, return `null`. + +```js +const findClosestMatchingNode = (node, selector) => { + for (let n = node; n.parentNode; n = n.parentNode) + if (n.matches && n.matches(selector)) return n; + return null; +}; +``` + +```js +findClosestMatchingNode(document.querySelector('span'), 'body'); // body +```