I was able to do something similar with a custom :this
pseudo selector. Is it possible to create custom jQuery selectors that navigate ancestors? e.g. a :closest or :parents selector
I could not find a way to solve it using anything else available (not without replacing/hacking Sizzle completely), but it would probably work with &
or #current
with a simple change.
Based on my previous answer you could probably do this:
// Add findThis method to jQuery (with a custom :this check)
jQuery.fn.findThis = function (selector) {
// If we have a :this selector
if (selector.indexOf('&') || selector.indexOf('#current') > 0) {
var ret = $();
for (var i = 0; i < this.length; i++) {
var el = this[i];
var id = el.id;
// If not id already, put in a temp (unique) id
el.id = 'id'+ new Date().getTime();
var selector2 = selector.replace('&', '#' + el.id).replace('#current', '#' + el.id);
ret = ret.add(jQuery(selector2, document));
// restore any original id
el.id = id;
}
ret.selector = selector;
return ret;
}
// do a normal find instead
return this.find(selector);
}
And use like this:
var current = current.findThis('#current > s.someclass');
var sameAsCurrent = current.findThis('&'); // kind of pointless, but works
var childOfCurrent = current.findThis('& > div');
The way it works is to add a temp selector to the "current" element, and replaces the chosen symbol (#current
or &
) with a selector for that temp id. It puts the original id back after the findThis
call.