jQuery Utility Methods

The utility methods that jQuery provides are very useful for doing routine programming tasks.
Here are some common jQuery utility methods. For more information, visit http://api.jquery.com/category/utilities/

$.trim():  This method removes leading and trailing white spaces.

$.trim('    lots of extra whitespace    '); // Will return lots of extra whitespace

$.each():  This method iterates over objects and arrays

$.each(['apple','banana','peach'], function(index, value) {
  console.log('index: ' + index + ' value: ' + value);
}); 

$.each({ firstname : 'laurent', lastname : 'tonon' }, function(key, value) {
  console.log(key + ' : ' + value);
});

$.inArray():  This method checks if a value is contained in an array. If found it returns the value’s index of the array. Returns -1 if the value is not found

var myArray = [ 23, 46, 31, 12 ];
if ($.inArray(31, myArray) !== -1) { // this will returns 2
  console.log('found it!');
}

$.extend():  This method merges the properties of the first passed object using the properties of the other passed objects as arguments. The first object is modified and returned by the method

var myFirstObject = { fruit : 'apple', vegetable: 'carrot' };
var mySecondObject = { fruit : 'banana' };
var resultingObject = $.extend(myFirstObject, mySecondObject); // Modifies the first object and returns the modified object
console.log(myFirstObject.fruit); // print banana
console.log(resultingObject.fruit); // print banana
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s