Last active
June 2, 2019 20:08
-
-
Save netsi1964/bf5988fdcc060fe915a7ce7a58558b51 to your computer and use it in GitHub Desktop.
Create list of selectors for all elements on a 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
const html = [...document.querySelectorAll("*")] | |
.map(e => { | |
let html = ""; | |
let ee = e, | |
id = "", | |
unique = false; | |
let selectors = []; | |
while (ee.parentNode && !id && !unique) { | |
const classes = [...ee.classList].sort().join("."); | |
const id = ee.getAttribute("id"); | |
let selector = ""; | |
selector += selector ? " > " : ""; | |
let subSelector = ""; | |
subSelector += ee.tagName.toLowerCase(); | |
subSelector += id ? "#" + id : ""; | |
subSelector += classes ? "." + classes : ""; | |
let matches = document.querySelectorAll(subSelector); | |
let match = -1; | |
[...matches].some((ele, i) => { | |
if (ele === e) { | |
match = i; | |
return true; | |
} | |
}); | |
if (matches.length > 1) { | |
subSelector += `:nth-child(${match + 1})`; | |
} | |
matches = document.querySelectorAll(subSelector); | |
if (matches.length === 1 && matches[0] === e) { | |
unique = true; | |
} else { | |
} | |
selectors.push(subSelector); | |
ee = ee.parentNode; | |
} | |
return `<div>${selectors.reverse().join(" > ")} {}</div>`; | |
}) | |
.join(""); | |
document.body.innerHTML += `<h2>Found these unique CSS selectors</h2><pre>${html}</pre>`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment