Skip to content

Instantly share code, notes, and snippets.

@emdagon
Forked from weaver/make-selector.js
Last active August 29, 2015 14:18
Show Gist options
  • Save emdagon/2a1ed64eb82b7ea7cefe to your computer and use it in GitHub Desktop.
Save emdagon/2a1ed64eb82b7ea7cefe to your computer and use it in GitHub Desktop.
// Create an absolute jQuery selector for a DOM element.
//
// + el - Element to select.
//
// Returns String selector.
function makeSelector(el) {
var tag, index, stack = [];
for (; el.parentNode; el = el.parentNode) {
tag = el.tagName;
for (index = 0; el.previousSibling;) {
el = el.previousSibling;
if (tag == el.tagName)
index += 1;
}
stack.unshift(tag + ':eq(' + index + ')');
}
return stack.join(' > ');
}
// Test makeSelector()
//
// + query - String, jQuery, or DOM Element
//
// Choose the first element in `query` and generate a selector for it.
// Log this to the console. Report an error if the selector doesn't
// select the original element.
//
// Returns nothing.
function testSelector(query) {
query = $(query);
var el = query.get(0),
selector = makeSelector(el);
console.log('Made selector', selector, 'for', el);
var probe = $(selector).get(0);
if (!probe === el)
console.error('Expected', el, 'not', probe);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment