I need to be able to get an unqiue selector for each element on a page.

For example, when I click on an element I want to do something like this:

$(document).click(function(){
    var sel = getUniqueSel(this);
});

So, after storing the sel value in a DB I can get that value and simply access the element by

var el = $(sel);

I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.

share|edit|retag|flag
1 upvote
 flag
Why cant you give the ones you are interested in an ID? Just curious? Are you really interested in every single object on the page? – mplungjan 4 mins ago
  upvote
 flag
  upvote
 flag
@mplungjan I want to store the selectors for all clicked elements on a page :), and this script will be included on many pages. – Cristy 2 mins ago
add / show 1 more comment

1 Answer

an edit has been made to this post; click to load

So long as things all have identifiers, you could do...

var selector = "#" + $(this).attr("id");

If you can't add these to make sure it works in all instances then you'll need to contrive a away by coupling the element type, attribute values and specific classes, but even then, without a unique identifier, no one thing can be uniquely identified necessarily.

share|edit|flag
  upvote
 flag
I can't assume that all elements have IDs. – Cristy 3 mins ago
  upvote
 flag
@Cristy Then you can't assume to get anything uniquely. – Grant Thomas 1 min ago
  upvote
 flag
I was thinking something like store the which nth-of-type (relative to the document) and which type is the clicked element. The position in the DOM is unique :) – Cristy 1 min ago
add comment

Your Answer

 

Not the answer you're looking for? Browse other questions tagged or ask your own question.