How to create custom selector in jQuery

We know jQuery has powerful collection on selectors. Even more jQuery allows us to extend selectors as per our requirement.

In addition to the class and id selectors, there are many selection expressions that use the colon syntax like (:odd, :even, :first, :input, etc.). If one of the existing selectors doesn’t fit your needs, jQuery provides you the flexibility to create your own.

jQuery.extend(jQuery.expr[':'], {

		emptyValue: function(obj){

			return $(obj).val() == ''
		}
	});

In this example, we are going to create a selector nonEmpty which selects the fields whose value is not empty. The object obj is passed in the function. The function can be as simple as one line or complex. Here, we have checked the value and returned its result.
Returned value must be boolean.
Now our new selector can be used as following

$('#formid input:emptyValue').css('border','1px red solid');

Using this statement, all input element in ‘#form’ form with empty value will be applied with given CSS.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.