Last active
July 24, 2019 04:46
-
-
Save saarmstrong/5e8d2ac45dfd76a2574f to your computer and use it in GitHub Desktop.
jQuery getSelector plugin: return jQuery selector string from a provided jQuery object.
This file contains 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
/* | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It should be nth-of-type instead of nth-child, otherwise doesn't work.