You are reading a page on Ben Weaver's Website.

Make a custom jQuery pseudo-selector

2010.03.30 Read More javascript jquery

Jquery can be extended with custom pseudo-selectors. Using pseudo-selectors improves code readability and avoids repetition. This example shows how to make a pseudo-selector called :named.

In a recent project, I wanted to find the elements with a name or data-name attribute in a form. There were a couple of places in the code that processed these elements, so to avoid repeating the query "[name], [data-name]", I extended jQuery with a pseudo-selector to use like this:

$("form").find(":named")

jQuery uses Sizzle, which can be extended in a number of ways. Adding a method to $.expr.filters, which is an alias for Sizzle.selectors, installs a new pseudo-selector. See the Pseudo-Selectors section in the Sizzle Documentation.

$.expr.filters.named = function(elem) {
  return !!(elem.getAttribute('name')
      || elem.getAttribute('data-name'));