In this blog, I will create a simple example for creating our own custom selector in jQuery. I will also create example to add a utility method to the jQuery object and to override an existing method in jQuery.
jQuery allows us to create our own custom selectors in case the existing selectors can't be used. For example purpose, lets say that the requirement is to format positive and negative numbers using custom selector. Format the positive numbers green and the negative numbers as red with value within brackets. It can be achieved via the code below.
jQuery also allows us to attach utility methods to the jQuery object by adding functions to the $. Here, we add a simple utility method which logs and alerts a message. The message is logged to the console if console is available (like in new browsers).
Here, first we create 2 custom selectors formatPos and formatNeg by adding them to $.expr[":"]. If the inner html of element is a number we return the true false bool value based on whether its positive or negative. Then in the button click we apply the selector by using $("div:formatPos") syntax. Once the button is clicked, the positive numbers become green and negative ones become red.
The next example overrides the isNumeric method. This is not recommended as jQuery might use the overridden functions internally. The override may cause all those functions to behave abnormally as well. For our example, we are using the new isNumeric method just to log to the console the results.
jQuery allows us to create our own custom selectors in case the existing selectors can't be used. For example purpose, lets say that the requirement is to format positive and negative numbers using custom selector. Format the positive numbers green and the negative numbers as red with value within brackets. It can be achieved via the code below.
jQuery also allows us to attach utility methods to the jQuery object by adding functions to the $. Here, we add a simple utility method which logs and alerts a message. The message is logged to the console if console is available (like in new browsers).
Here, first we create 2 custom selectors formatPos and formatNeg by adding them to $.expr[":"]. If the inner html of element is a number we return the true false bool value based on whether its positive or negative. Then in the button click we apply the selector by using $("div:formatPos") syntax. Once the button is clicked, the positive numbers become green and negative ones become red.
The next example overrides the isNumeric method. This is not recommended as jQuery might use the overridden functions internally. The override may cause all those functions to behave abnormally as well. For our example, we are using the new isNumeric method just to log to the console the results.