Created
October 14, 2010 18:54
-
-
Save weaver/626788 to your computer and use it in GitHub Desktop.
Create an absolute jQuery selector for a DOM element.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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