Skip to content

Instantly share code, notes, and snippets.

@arajajyothibabu
Created April 23, 2019 10:43
Show Gist options
  • Save arajajyothibabu/2f8189ea7c95793da9f59cdc7fe6ebb7 to your computer and use it in GitHub Desktop.
Save arajajyothibabu/2f8189ea7c95793da9f59cdc7fe6ebb7 to your computer and use it in GitHub Desktop.
Element Selector in DOM using JavaScript
const getSelector = (node) => {
let name = "";
if (node && node.localName) {
name = node.localName; //tag name
if (name === "html") { //DOM root FIXME: not sure with this
return name;
}
if (node.hasAttribute && node.hasAttribute("id")) { //checking for id
name += `#${node.getAttribute("id")}`;
} else {
if (node.classList && node.classList.length) { //checking for classes
name += `.${node.className.replace(" ", ".")}`;
}
if (node.parentNode) { //going upwards in the DOM tree
const similarChildren = node.parentNode.querySelectorAll(name);
if (similarChildren.length > 1) { //more than one similar node
const index = Array.prototype.indexOf.call(node.parentNode.children, node) + 1;
name = getSelector(node.parentNode) + `:nth-child(${index}) > ` + name;
} else { //only unique child
name = getSelector(node.parentNode) + ' > ' + name;
}
}
}
}
return name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment