In the previous articles, we explored jQuery and its functions, events, and effects, which help us make our interface more interactive and engaging. jQuery is a JavaScript library that allows you to manipulate the DOM objects dynamically without any vanilla JavaScript. In addition, jQuery provides us with some utility functions that help you perform common JS tasks concisely in a cross-browser-compatible manner.
In this article, we will learn how to use these utility functions to make our lives easier.
1. Manipulating Collections
Collections in JavaScript include all the data types that can contain more than 1 value, such as arrays, objects, lists, etc. There are several utility functions in jQuery to manipulate these collections, some of which we'll cover in this section:
$.each()
The .each() method is used to iterate through a collection and run a function for each element that matches the specified value.
Syntax:
$.each(collection, function(index, value){});
In the above syntax, the index refers to the item's index number, and the value refers to the current item. You can use this selector for the element.
Example:
Let's suppose we have an array of 3 items. Now, we want the items in the array to display in the alert box when we click a button. To do so, we will use the $.each() method as follows:
$(document).ready(function(){
$arr = ['Water', 'Coffee', 'Juice'];
$('#show').click(function(){
$.each($arr, function(index, value){
alert(this);
});
});
});
$.grep()
The .grep() method returns a new array or collection based on the specified condition. The new array only includes the elements that satisfy the given conditions.
Syntax:
$.grep(collection, function(parameters){ return conditions; });
Example:
Suppose we have an array with some number and want a new array with elements greater than or equal to 13 and lesser than 15 or greater than 15. To achieve that, we will use the .grep() method as follows:
$(document).ready(function(){
$arr = [10,11,12,13,14,15,16];
$('#show').click(function(){
$arr_2 = $.grep($arr, function(val_1, val_2, val_3){
return (val_1 >= 13 & val_2 <=15 || val_3 >15);
});
document.write($arr_2);
});
});
$.inArray()
This method returns the index of an element if it exists in an array or -1 if it does not. It is similar to the .indexOf() method that also returns the index number of an array element.
Syntax:
$.inArray(value, collection);
Example:
Suppose we have an array of five elements with different names. To find the index number of a particular name, we can use the .inArray() method as follows:
$(document).ready(function(){
$arr = ["John", "Smith", "Sasha", "Jennifer", "Angel"];
$('#find).click(function(){
alert($.inArray("Smith", $arr));
});
});
$.extent()
The $.extend() method allows you to combine the contents of 2 collections and store them into the first one. It modifies the properties of the first object using the properties of the second.
Syntax:
$.extend(Object_1, Object_2, [Object_N]);
In the above syntax, object_1 refers to the object to which the contents will be added, and object_2 refers to the object whose content will be copied. Object_N represents the ability to merge as many objects as you want.
An alternative syntax could be as follows:
$.extend(deep, target, object_1, object_N);
In the above syntax:
- deep: When this argument is true, the merging becomes recursive.
- target: This refers to the object to which the contents would be added, or the properties will be applied.
- Object_1, Object_N: The objects to be merged.
Example:
Suppose we have 2 string arrays and want to extend the first array. We will do it as follows with the .extend() method:
$(document).ready(function(){
$arr = ["John", "Smith", "Sasha", "Jennifer", "Angel"];
$arr_2 = ["a","b","c","d","e"];
$('#show').click(function(){
alert($.extend($arr, $arr_2));
});
});
2. Manipulating Strings and Data
Strings are the most commonly used data types, and whatever input the user gives through a textbox must be manipulated to use it. Therefore, jQuery provides various utility functions to manipulate strings and other data:
$.trim():
The $.trim() method allows you to cut the whitespace from a string.
Syntax:
$.trim(string);
Example:
Suppose we have a string with too much extra spacing at the beginning and end. We can get rid of that extra spacing via the .trim() method as follows:
$(document).ready(function(){
$str = " This String Had Too Much Space! ";
$('#show').click(function(){
alert($.trim($str));
});
});
.data():
This method is used to store arbitrary data for the DOM elements. It provides us with information regarding data.
Syntax:
$(selector).data(key, value);
In the above syntax, the key is a string or the name of the value to be stored, and the value is the data to be stored.
$(document).ready(function(){
$("#show").click(function(){
alert($.data($('#parent'), "test", 100));
});
});
3. Type Checking and Testing
With jQuery, you can also check the type of data being passed. It is helpful for validation and performing some actions based on the object type.
$.isArray():
The .isArray() method checks if an object is a JavaScript array. It returns true or false based on the object type.
Syntax:
$.isArray(object);
Example:
In the following example, I have declared an array and checked if it is an array or not:
$(document).ready(function(){
$arr = [1,2,3,4];
$("#show").click(function(){
alert($.isArray($arr)); //True
});
});
The following code returns false:
$(document).ready(function(){
$arr = 1;
$("#show").click(function(){
alert($.isArray($arr)); //False
});
});
$.isFunction()
This method checks if an object is a JavaScript function or not. It also returns a true or false value.
Syntax:
$.isFunction(object);
Example:
In the following example, I have defined a function and used .isFunction() to validate it.
function test()
{
}
$(document).ready(function(){
$arr = 1;
$("#show").click(function(){
alert($.isFunction(test)); //True
});
});
$.isNumeric()
$.isNumeric method checks if a value is numeric or not. It also returns true or false.
Syntax:
$.isNumeric(object/value);
You can also pass a direct value in this function.
Example:
$(document).ready(function(){
$("#check").click(function(){
alert($.isNumeric("Test")); //False
});
});
Example:
$(document).ready(function(){
$("#check").click(function(){
alert($.isNumeric(3)); //True
});
});
4. Miscellaneous
$.noop()
This method does nothing but is used as a default callback. The noop stands for no operation.
$.type()
The $.type() method is used to determine the data type of an object in JavaScript.
Syntax:
$.type(object);
You can pass a direct value to it as well.
Example:
$(document).ready(function(){
$("#check").click(function(){
alert($.type(4)); //Number
});
});
These are some jQuery utility functions that really come in handy at times. These are widely used to make web pages more dynamic and interactive. Try to use them in your practice projects to get a good hands-on experience.
Bingo! You have come a long way in learning jQuery. Keep it up and spend some time learning more things yourself. Web development is a vast subject; we cannot cover it all here. Therefore, spending time learning and implementing new things really helps you be a great we