Implicit iteration
We need to remember that a jQuery selector expression can always match zero, one, or multiple elements. We must allow for any of these scenarios when designing a plugin method. In this case, we are calling .hasClass(), which only examines the first matched element. Instead, we need to check each element independently and act on it.
The easiest way to guarantee proper behavior, regardless of the number of matched elements, is to always call .each() on the method context; this enforces implicit iteration, which is important for maintaining consistency between plugin and built-in methods. Within the .each() callback function, the second argument refers to each DOM element in turn, so we can adjust our code to separately test ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access