Skip to main content

How To Create A Custom Pseudo Selector With jQuery

By May 4, 2017Blog, Javascript, jQuery
Allure Web Solutions Code Snippet

In this blog post, I show how to create a custom pseudo selector with jQuery. This is useful in a few situations when you can avoid writing a long function that would perform the same action as the pseudo selector.

In the code below, we create the :nocontent selector which can be used to select all matching elements that are empty.

$.expr[":"].nocontent = function(obj, index, meta, stack) {
  // obj - is a current DOM element
  // index - the current loop index in stack
  // meta - meta data about your selector
  // stack - stack of all elements to loop

  // Return true to include current element
  // Return false to explude current element
  return !$.trim($(obj).text()).length && !$(obj).children().length;
};

// Credit: http://stackoverflow.com/a/7572288/3602355

 Example

The top div has a green background because it’s not empty and the bottom div is red because it is empty.

See the Pen Create Custom Pseudo Selector With jQuery by Mike Doubintchik (@allurewebsolutions) on CodePen.

allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017