Created
March 14, 2014 15:57
-
-
Save Tomalak/9550616 to your computer and use it in GitHub Desktop.
jQuery custom selector :count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jquery.custom-selectors.count.js | |
* | |
* custom selector for finding elements that have a certain child/descendant count | |
* | |
* Usage: $("td:count(div, 3)") - all <td> that have 3 <div> as direct children | |
* $("td:countAll(div, 3)") - all <td> that have 3 <div> as descendants | |
*/ | |
jQuery.extend(jQuery.expr[':'], ( | |
function () { | |
var metaParser = function(meta) { | |
var args = meta[3], | |
lastComma = args.lastIndexOf(","); | |
return { | |
selector: args.slice(0, lastComma), | |
count: parseInt(args.slice(lastComma + 1), 10) | |
}; | |
}; | |
return { | |
count: function(element, index, meta) { | |
var args = metaParser(meta); | |
return $(element).children(args.selector).length === args.count; | |
}, | |
countAll: function(element, index, meta) { | |
var args = metaParser(meta); | |
return $.find(args.selector, element).length === args.count; | |
} | |
}; | |
})() | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment