Last active
October 20, 2021 14:17
-
-
Save gaetanlegac/c81342dcd0572a7a4eb1f45b3dc55cb0 to your computer and use it in GitHub Desktop.
Deeply check if a HTML element is contained in one of the provided HTML elements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ElementOrSelector = HTMLElement | string; | |
export const deepContains = ( | |
parents: ElementOrSelector | ElementOrSelector[], | |
children: HTMLElement | |
): boolean => { | |
if (!Array.isArray(parents)) | |
parents = [parents]; | |
let node: HTMLElement | null = children; | |
while (node) { | |
for (const parent of parents) { | |
console.log('Checking if', parent, 'matches with', node); | |
if ( | |
// HTML Element | |
node === parent | |
|| | |
// CSS Selector | |
(typeof parent === 'string' && node.matches && node.matches(parent)) | |
) | |
return true; | |
} | |
node = node.parentNode as HTMLElement | null; | |
} | |
return false; | |
} | |
/* USAGE EXAMPLE: | |
Consider the following document: | |
<article id="article1"> | |
<header> | |
<h2>My Article</h2> | |
</header> | |
<footer> | |
<button>Like</button> | |
</footer> | |
</article> | |
const article = document.getElementById('article1'); | |
const button = document.querySelector('#article1 > footer > button'); | |
const header = document.querySelector('#article1 > header'); | |
The following statement returns true: | |
deepContains( article , button ); | |
deepContains([ button, article ], header ); | |
The following statement returns false: | |
deepContains( header , button ); | |
deepContains([ button, header ], article) ; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment