Writing a custom selector plugin

Now I am learning how to write a custom selector plugin in “Learning Jquery 4th edition”. I don’t understand this code snippet, so i need you help to make it clear to me?

(function($) {
$.extend($.expr[':'], {
group: function(element, index, matches, set) {
var num = parseInt(matches[3], 10);
if (isNaN(num)) {
return false;
}
return index % (num * 2) <num;
}
});
})(jQuery);

You need backticks instead of periods to format code in the forum. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

It helps if you can describe what you think the snippet is supposed to do, or at least what the book says it does, but I’ll take a crack at this.

$.expr is an object in jQuery’s selector engine, Sizzle. It holds references to all of Sizzle’s pseudo selectors (such as :not() or :first-child).

$.extend() is a function that takes two objects and extends the first with the second.

This code is extending Sizzle/jQuery’s expr object with another object, thus creating a new pseudo selector, :group. The intended use for this is, I think:

$.('.someClass').is(':group') // returns boolean

Exactly what this is for and how this works will be in the book. The function essentially takes an element, its index, an array that includes all of the matched data, and a set of all elements found (…maybe…?).

var num = parseInt(matches[3], 10);

This parses the 4th array element in the matches parameter as a base-10 integer. This seems to be the matched element’s inner text, so I’m not sure what the intent is here.

if (isNaN(num)) {
    return false;
}
    return index % (num * 2) <num;
}

If we didn’t get a number in the code above, we return false to indicate that there was no match. If it is a number, then we test to see if it’s within a grouping of elements that’s somehow defined by the element’s index.

Hope that helps.

thanks PortableStick so much for your help