Skip to content

Instantly share code, notes, and snippets.

@SeanJM
Last active September 29, 2015 18:01
Show Gist options
  • Save SeanJM/dcb14ba1aab7d714bc4f to your computer and use it in GitHub Desktop.
Save SeanJM/dcb14ba1aab7d714bc4f to your computer and use it in GitHub Desktop.
Get the CSS selector path for a Node (eg: div.className span#id div[data-attribute="value"]). Includes two separate functions, one which converts a Node to a selector, the other which generates a path)
function getNodePath (node) {
var path = [];
while (node) {
path.unshift(toSelector(node));
if (node === document.body || node.id.length > 0) {
return path.join(' ');
}
node = node.parentNode;
}
return path.join(' ');
}
function toSelector (node) {
var tagName = node.tagName.toLowerCase(),
attr = node.attributes,
hasId = node.id.length,
hasClass = node.className.length,
siblings = [].slice.call(node.parentNode.childNodes),
selector = [],
i;
for (i = siblings.length - 1; i >= 0; i--) {
// Ensure that only element nodes are in the 'siblings' array
if (siblings[i].nodeType !== 1) {
siblings.splice(i, 1);
}
}
// If a tag contains this character, it would be an invalid selector
if (!/:/.test(tagName)) {
selector.push(tagName);
}
if (hasId) {
selector.push('#' + node.id)
}
if (hasClass) {
selector.push('.' + node.className.trim().split(' ').join('.'));
} else if (!hasId) {
// Does not have a class or an ID : create attribute selector
for (i = 0, n = attr.length; i < n; i++) {
selector.push('[' + attr[i].name +'="' + attr[i].nodeValue + '"]');
}
}
if (siblings.length > 1) {
selector.push(':nth-child(' + (siblings.indexOf(node) + 1) + ')');
}
return selector.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment