get-selector.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. !(function ($, undefined) {
  2. $.fn.getSelector = function () {
  3. if (!this || !this.length) {
  4. return ;
  5. }
  6. function _getChildSelector(index) {
  7. if (typeof index === 'undefined') {
  8. return '';
  9. }
  10. index = index + 1;
  11. return ':nth-child(' + index + ')';
  12. }
  13. function _getIdAndClassNames($el) {
  14. var selector = '';
  15. // attach id if exists
  16. var elId = $el.attr('id');
  17. if(elId){
  18. selector += '#' + elId;
  19. }
  20. // attach class names if exists
  21. var classNames = $el.attr('class');
  22. if(classNames){
  23. selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
  24. }
  25. return selector;
  26. }
  27. // get all parents siblings index and element's tag name,
  28. // except html and body elements
  29. var selector = this.parents(':not(html,body)')
  30. .map(function() {
  31. var parentIndex = $(this).index();
  32. return this.tagName + _getChildSelector(parentIndex);
  33. })
  34. .get()
  35. .reverse()
  36. .join(' ');
  37. if (selector) {
  38. // get node name from the element itself
  39. selector += ' ' + this[0].nodeName +
  40. // get child selector from element ifself
  41. _getChildSelector(this.index());
  42. }
  43. selector += _getIdAndClassNames(this);
  44. return selector;
  45. }
  46. })(window.jQuery);