1

I'm trying to figure out the Sizzle extension API. In particular, I'm trying to get jQuery to recognize the sass-style & selector (referring to the 'current element').

For example, I'm trying to achieve the following result:

var current        = $('#current');
var sameAsCurrent  = current.find('&');
var childOfCurrent = current.find('& > div');

I've tried adding & as a finder and as a filter. I've even tried monkey-patching the jQuery library. I've had no luck with any of these approaches so far. Shouldn't this be one of the easiest selectors to add?

mhelvens
  • 4,225
  • 4
  • 31
  • 55
  • `var childOfCurrent = current.find(' > div');` – Arun P Johny Mar 03 '14 at 00:42
  • @ArunPJohny: Yes, I know. :-) But I'd like to get some consistency with SASS syntax, as well as learn about the Sizzle extension API. – mhelvens Mar 03 '14 at 00:46
  • @Joe: Unfortunately those references are all about custom *pseudo-selectors*, i.e., selectors starting with `:`. Indeed, that seems to be the only kind of help I could find with Google. But it's not what I'm after. – mhelvens Mar 03 '14 at 01:21

1 Answers1

0

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.

Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202