:nth-of-type() in jQuery / Sizzle?

后端 未结 3 1478
旧时难觅i
旧时难觅i 2020-11-30 08:46

It surprised me that Sizzle (the selector engine jQuery uses) comes with a built-in :nth-child() selector, but lacks an :nth-of-type() selector.

相关标签:
3条回答
  • 2020-11-30 09:21

    I can't pretend to know how nth-of-type is implemented, but jQuery does provide a mechanism by which you can create your own custom selector.

    The following question deals with custom selectors, and may provide a useful insight to you

    What useful custom jQuery selectors have you written?

    0 讨论(0)
  • 2020-11-30 09:31
    /**
     * Return true to include current element
     * Return false to exclude current element
     */
    $.expr[':']['nth-of-type'] = function(elem, i, match) {
        if (match[3].indexOf("n") === -1) return i + 1 == match[3];
        var parts = match[3].split("+");
        return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
    };
    

    Test case - (check in IE or rename the selector)

    You can of course add even & odd too:

    match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];
    

    0 讨论(0)
  • 2020-11-30 09:40

    the jQuery plugin moreSelectors has support for nth-of-type (and many other selectors). I suggest either using that, or simply implement a simple plugin that only implements the exact selectors you need. You should be able to copy-paste code from there.

    Happy hacking!

    0 讨论(0)
提交回复
热议问题