Skip to content

Instantly share code, notes, and snippets.

@josephwegner
Last active August 29, 2015 13:55
Show Gist options
  • Save josephwegner/8689420 to your computer and use it in GitHub Desktop.
Save josephwegner/8689420 to your computer and use it in GitHub Desktop.
CSS Selector Generator
var currentElement = false;
window.addEventListener("mousemove", function(e) {
var newElement = document.elementFromPoint(e.x, e.y);
if(newElement != currentElement) {
if(currentElement) {
currentElement.style["background-color"] = "white";
}
newElement.style["background-color"] = "blue";
currentElement = newElement
}
});
window.addEventListener("click", function(e) {
e.preventDefault();
if(currentElement) {
window.removeEventListener("mousemove");
window.removeEventListener("click");
}
var selector = getElementSelector(currentElement);
console.log(selector);
});
function getElementSelector(el){
var names = [];
while (el.parentNode){
if (el==el.ownerDocument.documentElement) names.unshift(el.tagName);
else{
for (var c=1,e=el;e.previousElementSibling;e=e.previousElementSibling,c++);
names.unshift(el.tagName+":nth-child("+c+")");
}
el=el.parentNode;
}
return names.join(" > ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment