How to find the shortest Selector

516 Views Asked by At

How can i get the shortest selector for any clicked element?
I want use this selector later to recover the same (or a nearly same) result.

Is there any existing method?

My ideas for that are searching with priority for:

  1. single-used ID
  2. multi-used ID with counter
  3. single-used name
  4. multi-used name with counter
  5. single-used classname
  6. multi-used classname with counter
  7. shortest parent path to 1.-6.

Not shure how to build a short path for maximum reliability and maximum flexibility (f.e. new parent-tags or a movement in the code).

1

There are 1 best solutions below

1
On

I would suggest something like:

When an element is clicked

  1. See if it has an ID, if so your selector is #<id>
  2. If it does not have an ID, generate a random identifier and assign it as the element's ID, your selector is #<generated-id>

i.e. something like:

var selector = '';

$('element').click(function() {
    var self = $(this);
    if(!self.is('[id]')) {
        var id = 'ljhlihj'; // replace with code to generate random ID
        self.attr('id', id);
    }
    selector = '#' + self.attr('id');
}