0

I need to get a full, working selector from the matched, or at least be able to cycle though a set of them

Here is an example of what I need. It works fine for the first two use cases, but not the last.

(function($){
      $.fn.getSelector = function(){
          return(this.selector);
      }
    })(jQuery)
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
  • For the last use case what result do you expect ? – Ion Sapoval Sep 05 '12 at 10:49
  • It was a hope more, that jquery would construct a valid selector string. I have no problem with iterating though the matched sets, but my experiments with that failed. – Mild Fuzz Sep 05 '12 at 10:51

1 Answers1

1

As a thumb rule, you can only use this.selector if the jQuery object is consturcted by one string selector. There are of course cases like find(''), where the selector is calculated and will be still available. (check the add function (and pushStack too) in jquery source). In add however it is not calculated (even if it would be easy to do in some cases).

What you can do is iterating through all the elements of the selector and calculating a valid selector path for them. There is no built in solution for this in jquery (AFAIK), but there are some examples even on stackoverflow on how to do this.

For example: How can i get selector from jQuery object There are a few usable answers here, like the one calculating the dom backwards. But you need to do that for every item, and even then it is possible that for a jquery collection there is no sane selector available that only matches the selected elements, therefore there will be a lot of false positive matches. So it's definitely not a perfect solution. Also you would need mached items.

What you could also do is override jquery's add method. It will work only if both the original object and the add method has a selector with a type of string. Check this fiddle. I'm sure it could be upgraded in many ways like also constructing the selector when the add method has jQuery object as the selector parameter and has it's selector property available, but it is a start.

Community
  • 1
  • 1
vinczemarton
  • 7,756
  • 6
  • 54
  • 86