Sizzle
When I talked about Sizzle, I decided not to overwhelm you with the library's extension capabilities, and now the time has come... In Sizzle, you can extend quite a few things:
Sizzle.selectors.matchSizzle.selectors.findSizzle.selectors.filterSizzle.selectors.attrHandleSizzle.selectors.pseudos
But we're only going to tackle extending pseudo-selectors, like these:
$("div:animated"); // find animated elements
$("div:hidden"); // find hidden div elements
$("div:visible"); // find visible div elementsWhy did I list only these filters? Simple — they're the only ones that aren't part of Sizzle and belong exclusively to jQuery. These are exactly the kind of plugins we'll be practicing to develop. Let's start with the :visible filter code:
// example for extending Sizzle inside jQuery
// extending Sizzle itself requires slightly different code
jQuery.expr.pseudos.visible = function( elem ) {
// check the width and height of each element in the selection
return !!( elem.offsetWidth || elem.offsetHeight);
};This code doesn't look complicated, but I'll still provide a skeleton for a new filter and add a few clarifications:
$.extend($.expr.pseudos, {
/**
* @param element DOM element
* @param i element's ordinal number
* @param match regex matching object
* @param elements array of all found DOM elements
*/
test: function(element, i, match, elements) {
/* our code goes here, and it will decide which elements make the cut */
return true || false; // include or exclude the element
}
})Alright, now let's try to solve the following task:
— We need to highlight links in the text depending on their type: external, internal, or anchor on the page.
The best solution would be selector filters like these:
Since this functionality isn't available out of the box, we'll write it ourselves. We don't need much for that (example only for the last one :external, working code on the sizzle.filter.html page):
Sizzle Documentation — the rather sparse official documentation
Last updated