Created
May 31, 2023 18:51
-
-
Save jean182/ce12ccde8cf0335ec80d66f4659c7d26 to your computer and use it in GitHub Desktop.
Get z-indexes from page.
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
/** | |
* Returns the z-index value of the element. | |
* | |
* | |
* @param element - The html element. | |
* @returns the element zIndex. | |
* | |
*/ | |
const getZIndex = (element) => getComputedStyle(element).zIndex; | |
/** | |
* Check if element has a non-auto zIndex. | |
* | |
* | |
* @param ele - The html element. | |
* @returns true if the element has a numeric zIndex. | |
* | |
*/ | |
const filterZIndex = (ele) => getComputedStyle(ele).zIndex !== "auto"; | |
/** | |
* Sort callback to verify if the zIndex is bigger than the other. | |
* | |
* | |
* @param a - The first html element to compare. | |
* @param b - The second html element to compare. | |
* @returns a number. | |
* | |
*/ | |
const sortElementByZIndex = (a, b) => { | |
const firstIndex = getZIndex(a); | |
const secondIndex = getZIndex(b); | |
return Number(firstIndex) - Number(secondIndex); | |
}; | |
/** | |
* Returns a sorted array of all the elements with zIndex based on this value. | |
* | |
* | |
* @returns the sorted html elements. | |
* | |
*/ | |
const sortElementsByZIndex = () => | |
[...document.querySelectorAll("*")] | |
.filter(filterZIndex) | |
.sort(sortElementByZIndex); | |
/** | |
* Returns an array containing all the zIndexes of the elements | |
* | |
* | |
* @returns the number array of all zIndexes. | |
* | |
*/ | |
const getZIndexes = () => sortElementsByZIndex().map(getZIndex); | |
/** | |
* Prints the zIndex with the respective element. | |
* | |
*/ | |
const printElementsWithZIndex = () => | |
sortElementsByZIndex().forEach(ele => { | |
const zIndex = getZIndex(ele); | |
console.log("Index:", zIndex); | |
console.log("element"); | |
console.log(ele); | |
console.log("------------------------"); | |
}); | |
/** | |
* Function to get an object with all the zIndexes in the codebase with the amount of times used. | |
* | |
* | |
* @param ele - The html element. | |
* @returns An object containing the zIndex as the key and the amount of times it was used. | |
* | |
*/ | |
const getUniqueZIndexes = () => | |
getZIndexes().reduce((prev, cur) => { | |
prev[cur] = (prev[cur] || 0) + 1; | |
return prev; | |
}, {}); | |
/** | |
* The number of times a numeric zIndex was used. | |
* | |
* | |
* @param ele - The html element. | |
* @returns the number of times a numeric zIndex was used across the whole document. | |
* | |
*/ | |
const countZIndexes = () => Object.values(getUniqueZIndexes).reduce( | |
(total, current) => total + current | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment