Web App Development

Writing custom jQuery selectors

jQuery supports a lot of DOM element selectors natively. However it does not provide some functionality, for example filtering by CSS values. In these cases you can use the filter method or add a filter to jQuery's selector engine Sizzle.

jQuery provides an alias for the Sizzle filter object Sizzle.selectors.filter. Below is the complete code for adding an "rgbColor" filter to this object -  $.expr[":"]:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<div style="color:red">Hello</div>
<div>world</div>
<div style="color:black">and</div>
<div style="color:rgb(50,150,0)">jQuery.</div>

<script>
$.expr[":"].rgbColor = function(element, index, customSelectorParts)
{
var selectorArguments = customSelectorParts[3];

if (selectorArguments == undefined)
{
var selectorRgb = "0,0,0";
}
else
{
var selectorRgb = selectorArguments.replace(/ /g, "");
}
var elementColor = $(element).css("color");
var elementRgb = elementColor.replace("rgb(","").replace(")","").replace(/ /g, "");

return elementRgb == selectorRgb;
}

$("div:rgbColor").append(" - matches div:rgbColor -");
$("div:not(:rgbColor)").append(" - matches not(div:rgbColor)-");
$("div:rgbColor(255,0,0)").append( " - matches div:rgbColor(255,0,0) - ");
</script>

Which gives us:

The filter function needs to return a boolean value indicating whether the element matches the selector.

Filters can accept arguments, for example rgb values in the code above. The third argument to the filter function is an array containing the parsed parts of the selector. For example these are the three values  for customSelectorParts:

[":rgbColor", "rgbColor", undefined, undefined, index: 0, input: ":rgbColor"]
[":rgbColor", "rgbColor", undefined, undefined, index: 0, input: ":rgbColor"]
[":rgbColor(255,0,0)", "rgbColor", "", "255,0,0", index: 0, input: ":rgbColor(255,0,0)"] 

So the value at customSelectorParts[3] gives us the filter arguments.

A fourth argument - not included in the example code - gives the list of all elements that the filter is run against. The second argument (index) indicates the position of the currently filtered element in that list.

Comments


Follow me on Twitter