Skip to content

Instantly share code, notes, and snippets.

@benhodgson
Created October 30, 2010 00:34
Show Gist options
  • Save benhodgson/654724 to your computer and use it in GitHub Desktop.
Save benhodgson/654724 to your computer and use it in GitHub Desktop.
Builds a jQuery selector string that selects the given DOM element (adapted from http://snippets.dzone.com/posts/show/3754)
var getjQuerySelector = (function() {
function siblingIndexPseudoSelector(el) {
var sibsBefore = 0,
sibsAfter = 0,
sib;
for (sib = el.previousSibling; sib; sib = sib.previousSibling) {
if(sib.nodeType == 1 && sib.tagName == el.tagName) {
sibsBefore += 1;
}
}
for (sib = el.nextSibling; sib; sib = sib.nextSibling) {
if(sib.nodeType == 1 && sib.tagName == el.tagName) {
sibsAfter += 1;
}
}
return (sibsBefore + sibsAfter == 0) ? '' : ':eq('+sibsBefore+')';
};
function buildRoute(el, route) {
route = route || [];
if(el && el.nodeType === 1) {
if(el.id) {
route.push("#" + el.id);
} else {
route.push(el.tagName.toLowerCase() + siblingIndexPseudoSelector(el));
return buildRoute(el.parentNode, route);
}
}
return route;
};
return function(el) {
return buildRoute(el).reverse().join('>');
};
})();
@benhodgson
Copy link
Author

Sure. A really simple example:

getjQuerySelector(document.getElementById('my_element')) === '#my_element'

It also builds more complex selectors, such as:

getjQuerySelector(document.body) === 'document>body'

or:

getjQuerySelector(document.body.childNodes[3]) === 'html>body>script:eq(0)'

@benhodgson
Copy link
Author

The goal was to be able to serialise the position of a given DOM element in a way that could be used to select that element on an identical page at some point in the future (specifically, another instance of the same page). My main motivation for writing this is that XPath selectors are no longer available in jQuery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment