Skip to content

Instantly share code, notes, and snippets.

@malko
Last active December 20, 2015 06:39
Show Gist options
  • Save malko/6087537 to your computer and use it in GitHub Desktop.
Save malko/6087537 to your computer and use it in GitHub Desktop.
return a querySelector for given DOMElement
/**
* return a selector to use with document.querySelector to retrieve given node
* @param {DOMElement} node
* @returns {string}
*/
function getSelector(node){
// check for node.id avoiding autogenerated ids by ignoring any ids containing numeric values
// and checking that the id is unique in the document.
if (node.id && node.id.match(/^\D+$/) && document.querySelectorAll(node.id).length === 1) {
return '#' + node.id;
}
// if node is body don't make any other lookup
if (node === document.body) {
return 'body';
}
// making a "more complex" node selector
var parent = node.parentNode, tagName = node.tagName;
// if only one child of type inside the parent made a simple tag selector
if (parent.querySelector(tagName).length === 1) {
return getSelector(parent) + '>' + tagName;
}
var prevSibling = node, nthOfType = 1;
// finally end up selecting the node by its nthOfType
while(prevSibling = prevSibling.previousElementSibling) {
prevSibling.tagName === tagName && ++nthOfType;
}
return getSelector(parent) + '>' + tagName + ':nth-of-type(' + nthOfType + ')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment