Skip to content

Instantly share code, notes, and snippets.

@weaver
Created October 14, 2010 18:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save weaver/626788 to your computer and use it in GitHub Desktop.
Save weaver/626788 to your computer and use it in GitHub Desktop.
Create an absolute jQuery selector for a DOM element.
// 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