Yes, you could do this. But with a few caveats. In order to be able to guarantee that selectors are unique, you'd need to use :nth-child() which isn't universally supported. If you're then wanting to put these CSS selectors into CSS files, it won't work in all browsers.
I'd do it with something like this:
function () {
if (this.id) {
return sendToServer('#' + this.id);
}
var parent = this.parentNode;
var selector = '>' + this.nodeName + ':nth-child(' + getChildNumber(this) ')';
while (!parent.id && parent.nodeName.toLowerCase() !== 'body') {
selector = '>' + this.nodeName + ':nth-child(' + getChildNumber(parent) + ')' + selector;
parent = parent.parentNode;
}
if (parent.nodeName === 'body') {
selector = 'body' + selector;
} else {
selector = '#' + parent.id + selector;
}
return sendToServer(selector);
}
Then add that to your click handler for each element you want to model. I'll leave you to implement getChildNumber().
Edit: Just seen your comment about it being 3rd party code... so you could add an event argument, replace all instances of this with event.target and then just attach the function to window's click event if that's easier.
answered 2011-12-21T10:35:20.790