Skip to content

Instantly share code, notes, and snippets.

@saarmstrong
Last active July 24, 2019 04:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save saarmstrong/5e8d2ac45dfd76a2574f to your computer and use it in GitHub Desktop.
Save saarmstrong/5e8d2ac45dfd76a2574f to your computer and use it in GitHub Desktop.
jQuery getSelector plugin: return jQuery selector string from a provided jQuery object.
/*
* jquery.getselector.js
*
* Get the CSS Selector string for a provided jQuery object.
*
* Based heavily on jquery-getpath (http://davecardwell.co.uk/javascript/jquery/plugins/jquery-getpath/),
* and this xPath SO answer (http://stackoverflow.com/a/3454579).
*
* Usage: var select = $('#foo').getSelector();
*/
(function($){
$.fn.getSelector = function() {
element = this[0];
// Get the xpath for this element.
// This was easier than calculating the DOM using jQuery, for now.
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode ) {
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
// Return CSS selector for the calculated xpath
return xpath
.substr(1)
.replace(/\//g, ' > ')
.replace(/\[(\d+)\]/g, function($0, i) { return ':nth-child('+i+')'; });
};
})(jQuery);
@Tora-Bora
Copy link

It should be nth-of-type instead of nth-child, otherwise doesn't work.

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