Skip to content

Instantly share code, notes, and snippets.

@Tomalak
Created March 14, 2014 15:57
Show Gist options
  • Save Tomalak/9550616 to your computer and use it in GitHub Desktop.
Save Tomalak/9550616 to your computer and use it in GitHub Desktop.
jQuery custom selector :count
/* 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