jQuery General UtilitiesS2C Home « jQuery General Utilities

In this lesson we look at the general utilities jQuery has to offer along with some jQuery global object properties.

The methods in this suite can save you writing a lot of JavaScript code so it is definitely worth familiarizing yourself with them.

  • The general utility methods are all class methods, do NOT return a jQuery object and are not suitable for chaining.
General Utilities & Global Object Properties Description
General Utility Methods
jQuery.contains()Return a boolean dependant upon whether a DOM element is within another DOM element.
jQuery.each()A generic iterator function used to iterate over objects and arrays.
jQuery.extend()Merge the contents of two or more objects into the first specified object.
jQuery.globalEval()Execute some JavaScript code at global scope.
jQuery.grep()Creates a new array, from the elements of an existing array meeting the requirements of a filter function, without affecting the contents of the original array.
jQuery.inArray()Return a number denoting the index position within the array containing the specified value.
jQuery.makeArray()Return a JavaScript Array object created from an array-like object.
jQuery.map()Return a JavaScript Array object translated from an array or object.
jQuery.merge()Merge the contents of two or more objects into the first specified object, optionally making the merge recursive.
jQuery.noop()Used to pass around an empty function.
jQuery.now() **DEPRECATED**
Shorthand for getting the current time.
jQuery.parseHTMLParse a string into an array of DOM nodes.
jQuery.parseJSON **DEPRECATED**
Return a JavaScript Object object created from the specified well-formed JSON string.
jQuery.parseXMLReturn an XML document created from the parsed string.
jQuery.trim() **DEPRECATED**
Remove whitespace from beginning and end of a string.
jQuery.type() **DEPRECATED**
Return a string representing the internal JavaScript [[Class]] of an object.
jQuery.unique() **DEPRECATED**
Return an array of sorted DOM elements with duplicates removed.
jQuery.uniqueSort()Return an array of sorted DOM elements with duplicates removed.
Global Object Properties
jQuery.boxModel **REMOVED**
Asserts whether the user's current browser page is being rendered using the W3C CSS Box Model.
jQuery.browser **REMOVED**
Contains flag information for the user agent extracted from navigator.userAgent.
jQuery.support **DEPRECATED**
Collection of properties representing the presence of different browser features or bugs.

General Utility Methods

The jQuery.contains() Method  Top

Return a boolean dependant upon whether a DOM element is within another DOM element.

We use this methods only signature jQuery.contains( outer, inner ) in our example below.

In the example below when we press the button the first time we check to see if document.documentElement (the <html> tag) contains document.body (the <body> tag), which returns true. Then we check to see if document.body (the <body> tag) contains document.documentElement (the <html> tag), which returns false.



$(function(){
  $('#btn9').one('click', function(){
    $('#div9').append('Does html contain body? : ' +
                       jQuery.contains( document.documentElement, document.body ) + '<br>');
    $('#div9').append('Does body contain html? : ' + 
                       jQuery.contains( document.body, document.documentElement ) + '<br>');
  });
});

div9. Some initial text.

Press the button below to action the above code:


The jQuery.each() Method  Top

A generic iterator function used to iterate over objects and arrays.

We use this methods only signature jQuery.each( collection, function(iterator, value) ) in our example below.

In the example below when we press the left button the first time we create an array and iterate over it.

When we press the right button the first time we create an object and iterate over it.



$(function(){
  $('#btn10').one('click', function(){
    var arr0 = [ 7, 2, 2, 5 ];
    $.each(arr0, function(index, value) {
      $('#div10').append( index + ': ' + value + '<br>');
    });
  });
  $('#btn11').one('click', function(){
    var obj = {"str1":"A stitch in time ",
               "str2":"Saves nine"};
    $.each(obj, function(key, value) {
      $('#div10').append( key + ': ' + value + '<br>');
    });
  });
});

div10. Some initial text.

Press the button below to action the above code:

           


The jQuery.extend() Method  Top

Merge the contents of two or more objects into the first specified object.

We use this methods jQuery.extend( target [, object1] [, objectN] ) signature in our examples below, which will merge the contents of two or more objects into the first specified object.

An example of this methods second signature jQuery.extend( [deep], target, object1 [, objectN] ), which will merge the contents of two or more objects into the first specified object, optionally making the merge recursive, is available in the reference section.

In the example below when we press the left button we create two objects obj1 and obj2 and then merge them together using jQuery.extend(). We then output a message displaying the new merged map for obj1. If you look at the output map displayed you will notice how the object map for the skills key gets overwritten and we lose some data as described under the Reference Description heading for the method.

When we press the right button below we create two objects obj1 and obj2 and then merge them together using jQuery.extend(). The difference here with the signature is the target; what we are doing is passing an empty object which will then get passed to the target object on return as descibed under the Reference Description heading for the method. We then output a message displaying the new merged map for target. Once again if you look at the output map displayed you will notice how the object map for the skills key gets overwritten and we lose some data because we are not doing a recursive merge of the objects.



$(function(){
  $('#btn12').one('click', function(){
    var obj1 = {species: 'penguin', skills: {flight: 'no', swim: 'yes'}, climate: 'cold'};
    var obj2 = {skills: {lactates: 'no'}, eats: 'fish'};
    $.extend(obj1, obj2);
    $('#div11').append('<pre>' + JSON.stringify(obj1) + ''</pre>'<br>');
  });
  $('#btn13').one('click', function(){
    var obj1 = {species: 'penguin', skills: {flight: 'no', swim: 'yes'}, climate: 'cold'};
    var obj2 = {skills: {lactates: 'no'}, eats: 'fish'};
    var target = $.extend({}, obj1, obj2);
    $('#div11').append('<pre>' + JSON.stringify(target));
  });
});

div11. Some initial text.

Press the button below to action the above code:

            


The jQuery.globalEval() Method  Top

Execute some JavaScript code at global scope.

We use this methods only signature jQuery.globalEval( code ) in our examples below.

In the example below when we press the left button we run the function globalEvalTest() which uses the jQuery.globalEval() jQuery General utility method to place a property on the window object. We then access this variable outside the function scope and display a message showing the variable ourMessage can be accessed globally.

When we press the right button we run the function globalEvalTest2() which uses the jQuery.globalEval() jQuery General utility method to place a property on the window object. We then use $.ajax() to run an external JavaScript file url: "../js/test.js" . within this external script we display the variable ourMessage2 as part of a display a message showing the variable can be accessed globally.


$(function(){
  $('#btn15').one('click', function(){
    function globalEvalTest(){
      $.globalEval("var ourMessage = '*** A message ***';");
    }
    globalEvalTest();
    $('#div13').append('Can we access ourMessage globally? ' + ourMessage + '<br>');
  });
  $('#btn16').one('click', function(){
    function globalEvalTest2(){
      $.globalEval("var ourMessage2 = '*** Message 2 ***';");
    }
    globalEvalTest2();
    $.ajax({
      type: "GET",
      url: "../js/test.js",
      dataType: "script"
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/test.js")
 * is shown below.
 */
$(function(){
  var someText = 'Some text to pass across ';
  $('#div13').append('Message: ' + someText + ourMessage2 + '<br>');
});

div13. Some initial text.

Press the button below to action the above code:

            


The jQuery.grep() Method  Top

Creates a new array, from the elements of an existing array meeting the requirements of a filter function, without affecting the contents of the original array.

We use this methods only signature jQuery.grep( array, function(elementOfArray, indexInArray) [, invert] ) in our example below.

When we press the top button the first time we create an array of values which we pass through the jQuery.grep() General utility method. We set the elementOfArray parameter to != 2 and the indexInArray value to > 7. Therefore starting at index position '8' our new array will return all items to our new array that do not equal the value '2'.

When we press the bottom button the first time we create an array of values which we pass through the jQuery.grep() General utility method using the invert option. We set the elementOfArray parameter to != 2 and the indexInArray value to > 7. With the invert option set, our new array will only contain elements that return false. Therefore the new array will contain all elements before index position '8' and all elements after this index position that equal the value '2'.



$(function(){
  $('#btn5').one('click', function(){
    var arr0 = [ 7, 2, 2, 5, 3, 6, 0, 8, 9, 1, 9, 5, 6, 2, 2, 5 ];
    var arr1 = jQuery.grep(arr0, function(n, i) {
   	  return (n != 2 && i > 7);
    });
    $('#div5').append('The new array contains the following values: ' + arr1 + '<br>');
  });
  $('#btn6').one('click', function(){
    var arr0 = [ 7, 2, 2, 5, 3, 6, 0, 8, 9, 1, 9, 5, 6, 2, 2, 5 ];
    var arr1 = jQuery.grep(arr0, function(n, i) {
   	  return (n != 2 && i > 7);
    }, true );
    $('#div5').append('The new array contains the following values: ' + arr1 + '<br>');
  });
});

div5. Some initial text.

Press the button below to action the above code:




The jQuery.inArray() Method  Top

Return a number denoting the index position within the array containing the specified value.

We use this methods only signature jQuery.inArray( value, array [, fromIndex] ) in our example below.

When we press the button the first time we create an array and then output a message showing the index position of the item with a value of 'tie using the jQuery.inArray() general utility method. This outputs a message showing the index as 2. We then output another message showing the index position of the item with a value of 'tie using the $.inArray() general utility method. This outputs a message showing the index as -1. This is because the second time we set the fromIndex parameter to '3' and so the search starts from that index. The 'tie' item is in position 2 (index starts at 0) and therefore we get a value of -1 returned, which equates to 'not found'



$(function(){
  $('#btn18').one('click', function(){
    var arr0 = [ 'belt', 'boots', 'tie', 'bracers', 'shirt' ];
    $('#div14').append('index of tie in array is: ' +  $.inArray( 'tie', arr0 ) + '<br>');
    $('#div14').append('index of tie in array is: ' +  $.inArray( 'tie', arr0, 3 ));
  });
});

div14. Some initial text.

Press the button below to action the above code:


The jQuery.makeArray() Method  Top

Return a JavaScript Array object created from an array-like object.

We use this methods only signature jQuery.makeArray( object ) in our example below.

When we press the button the first time we create a variable from a node list and test to see if it is an array using the jQuery.isArray() type utility method which returns false.

We then create another variable from the first variable using the jQuery.makeArray( object ) general utility method. We then test this variable against the jQuery.isArray() type utility method which returns true.



$(function(){
  $('#btn1').one('click', function(){
    var pElements = document.getElementsByTagName('p');
    $('#div1').append('Is pElements an Array object? ' +  $.isArray( pElements ) + '<br>');
    var ourArray = jQuery.makeArray(pElements);
    $('#div1').append('Is ourArray an Array object? ' +  $.isArray( ourArray ) + '<br>');
  });
});

div1. Some initial text.

Press the button below to action the above code:


The jQuery.map() Method  Top

Return a JavaScript Array object translated from an array or object.

We use this methods only signature jQuery.map( arrayOrObject, callback( value, indexOrKey ) ) in our example below.

When we press the button the first time we create an an object and then flatten it to an array using the jQuery.map() jQuery General utility method. An interesting thing to note is how we lose the original skills key in the flattening. You can use the jQuery.extend() method for these situations.



$(function(){
  $('#btn19').one('click', function(){
    var obj1 = {species: 'penguin', skills: {flight: 'no', swim: 'yes'}, climate: 'cold'};
    arr0 = $.map( obj1, function(val, i) { return val };
    $('#div15').append('Our new array holds the values: '  + JSON.stringify(arr0));
  });
});

div15. Some initial text.

Press the button below to action the above code:


The jQuery.merge() Method  Top

Merge the contents of two or more objects into the first specified object, optionally making the merge recursive.

We use this methods only signature jQuery.merge( first, second ) in our example below.

When we press the button the first time we create an an object and then flatten it to an array using the jQuery.merge() jQuery General utility method. An interesting thing to note is how we lose the original skills key in the flattening. You can use the jQuery.extend() method for these situations.



$(function(){
  $('#btn20').one('click', function(){
    var arr0 = [7, 4, 3, 1, 5];
    var arr1 = [5, 1, 3, 4, 7];
    $.merge( arr0, arr1 );
    $('#div16').append('First array values: ' + JSON.stringify(arr0) + '<br>');
    $('#div16').append('Second array is unchanged: ' + JSON.stringify(arr1));
  });
});

div16. Some initial text.

Press the button below to action the above code:


The jQuery.noop() Method  Top

Used to pass around an empty function.

Details of the jQuery.noop() method can be found in the reference section.

The jQuery.now() Method     **DEPRECATED** Top

Shorthand for getting the current time.

We use this methods only signature jQuery.now() ) in our example below.

When we press the button the first time we display a message for the longhand version of the current time using (new Date).getTime() and our shorthand version using the jQuery.now() jQuery General utility method.



$(function(){
  $('#btn2').one('click', function(){
    $('#div2').append((new Date).getTime() + '<br>');
    $('#div2').append($.now() + '<br>');
  });
});

div2. Some initial text.

Press the button below to action the above code:


The jQuery.parseHTML() Method  Top

Parse a string into an array of DOM nodes.

We use this methods only signature jQuery.parseHTML( data [, context ] [, keepScripts ] ) in our example below.

In the example below when we press the button the first time we parse some well formed HTML to the division with an id of 'div19' and then print out the DOM nodes.



$(function(){
  $('#btn23').one('click', function(){
    // Add some HTML
    parsedHtml = $.parseHTML( "Sentence has <strong>strongly typed text</strong> in it.<br />" ); 
    $('#div19').append(parsedHtml);
    // Append parsed HTML node names
    $.each( parsedHtml, function( i, el ) {
      $('#div19').append( el.nodeName + "<br />" );
    });
  });
});

div19. Our parsed HTML and nodes appear after 'btn23' is clicked.

Press the button below to action the above code:


The jQuery.parseJSON() Method     **DEPRECATED** Top

Return a JavaScript Object object created from the specified well-formed JSON string.

This method was deprecated in jQuery 3.0.

We use this methods only signature jQuery.parseJSON( json ) in our example below.

When we press the button we parse some well formed JSON to a variable. Then we output a message displaying the properties of the Object object we created.



$(function(){
  $('#btn8').one('click', function(){
    var obj = jQuery.parseJSON('{"str1":"A stitch in time ","str2":"Saves nine"}');
    $('#div8').append(obj.str1 + obj.str2);
  });
});

div8. Some initial text.

Press the button below to action the above code:


The jQuery.parseXML() Method  Top

Return an XML document created from the parsed string.

We use this methods only signature jQuery.parseXML( data ) in our example below.

When we press the button the first time we parse some well formed XML to a variable and then convert the variable to a jQuery object. After this we iterate over the xml nodes to print out some fictitious diary entries.



$(function(){
  $('#btn21').one('click', function(){
    var xml = "<xml version='1.0'>" +
    "<week date='01/01/2012 '><day activity='shopping '><loc>London</loc></day></week>" +
    "<week date='02/01/2012 '><day activity='driving '><loc>Cardiff</loc></day></week>" +
    "<week date='03/01/2012 '><day activity='eating '><loc>Glasgow</loc></day></week></xml>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc );
    
    // Print Diary details
    $($xml).find('week').each(function() {
      $('#div17').append($(this).attr('date'));
      $('#div17').append($(this).find('day').attr('activity'));
      $('#div17').append($(this).find('loc').text() + "<br>");
    });
  });
});

div17. Some initial text.

Press the button below to action the above code:


The jQuery.trim() Method     **DEPRECATED** Top

Remove whitespace from beginning and end of a string.

We use this methods only signature jQuery.trim( str ) in our example below.

When we press the button the first time we create a variable and display it before and after trimming within some preformatted text.



$(function(){
  $('#btn3').one('click', function(){
    var ourString = '  A stitch in time saves nine.   ';
    $('#div3').append( '<pre>+++' + ourString + '+++' + '</pre>'<br>');
    $('#div3').append( '<pre>+++' + $.trim( ourString ) + '+++' + '</pre><br>');
  });
});

div3. Some initial text.

Press the button below to action the above code:


The jQuery.type() Method     **DEPRECATED** Top

Return a string representing the internal JavaScript [[Class]] of an object.

We use this methods only signature jQuery.type( object ) in our example below.

When we press the button the first time, we create an array of objects and display their internal class.


$(function(){
  $('#btn4').one('click', function(){
    var arr1 = [obj0 = undefined, obj1 = null, obj2 = new Array(), obj3 = [], 
                obj4 = new Boolean(), obj5 = true, obj6 = new Date(), obj7 = new Function, 
                obj8 = function(){}, obj9 = new Number, obj10 = 3, obj11 = new Object, 
                obj12 = { a: 'b' }, obj13 = new RegExp, obj14 = (/regexp/), 
                obj15 = new String, obj16 = 'aaa'];
    for (var i=0; i<arr1.length; i++) {
      $('#div4').append('The Internal [[Class]] of obj' + i + ' is? ' +
                        $.type( arr1[i] ) + '<br>');
    }
  });
});

div4. Some initial text.

Press the button below to action the above code:


The jQuery.unique() Method     **DEPRECATED** Top

Return an array of sorted DOM elements with duplicates removed.

This method was deprecated in jQuery 3.0.

We use this methods only signature jQuery.unique( array ) in our example below.

When we press the button the first time, we create an array variable of the table DOM elements on the page. There are three tables on the page comprised of the 'Syntax' and 'Parameter' tables above, both of which have a class of 'javatable' and the 'Other Tutorial Sites' table within the footer of the page. We then concatenate onto this array and output a message displaying the array length. After this we use the jQuery.unique() method on the array, which removes the duplicates we added to the array. Finally we output a message displaying the array length again.



$(function(){
  $('#btn7').one('click', function(){
    var domElem = $('table').get();
    domElem = domElem.concat($('.javatable').get());
    $('#div7').append('<code>domElem</code> contains: ' + domElem.length + ' tables.<br>');
    domElem = jQuery.unique(domElem);
    $('#div7').append('<code>domElem</code> contains: ' + domElem.length + ' tables.<br>');
  });
});

div7. Some initial text.

Press the button below to action the above code:


The jQuery.uniqueSort() Method  Top

Return an array of sorted DOM elements with duplicates removed.

We use this methods only signature jQuery.unique( array ) in our example below.

When we press the button the first time, we create an array variable of the table DOM elements on the page. There are three tables on the page comprised of the 'Syntax' and 'Parameter' tables above, both of which have a class of 'javatable' and the 'Other Tutorial Sites' table within the footer of the page. We then concatenate onto this array and output a message displaying the array length. After this we use the jQuery.uniqueSort() method on the array, which removes the duplicates we added to the array. Finally we output a message displaying the array length again.



$(function(){
  $('#btn24').one('click', function(){
    var domElem = $('table').get();
    domElem = domElem.concat($('.javatable').get());
    $('#div20').append('<code>domElem</code> contains: ' + domElem.length + ' tables.<br>');
    domElem = jQuery.uniqueSort(domElem);
    $('#div20').append('<code>domElem</code> contains: ' + domElem.length + ' tables.<br>');
  });
});

div20. Some initial text.

Press the button below to action the above code:


Global Object Properties

The jQuery.boxModel Property     **REMOVED**  Top

Asserts whether the user's current browser page is being rendered using the W3C CSS Box Model.

This method was deprecated in jQuery 1.3 and so we are just showing it for completeness.

  • From jQuery version 1.3 onwards, use the jQuery.support property, which contains a collection of properties representing the presence of different browser features or bugs; useful for feature detection.

The jQuery.browser Property     **REMOVED**  Top

Contains flag information for the user agent extracted from navigator.userAgent.

This method was deprecated in jQuery 1.3 and removed in jQuery 3.5 so we are just showing it for completeness.

  • From jQuery version 1.3 onwards, use the jQuery.support property, which contains a collection of properties representing the presence of different browser features or bugs; useful for feature detection.

The jQuery.support Property     **DEPRECATED** Top

Contains flag information for the user agent extracted from navigator.userAgent.

This method was deprecated in jQuery 1.9.

When we press the button the first time, we iterate through the jQuery.support property copying each element to a new array. We then sort and print the settings (which may vary dependant upon the browser you are using).



$(function(){
  $('#btn22').one('click', function(){
    $('#div18').append('jQuery $.support properties for your browser: ' + '<br>');
    var arr0 = [];
    $.each($.support, function(index, value) {
      arr0.push(index + ': ' + value);
    });
    arr0.sort();
    $.each(arr0, function(index, value) {
      $('#div18').append( index + ': ' + value + '<br>');
    });
  });
});

div18. Some initial text.

Press the button below to action the above code:


Lesson 9 Complete

In this lesson we took a look at the jQuery general utility methods and some jQuery global object properties.

Related Tutorials

jQuery 3.5 Intermediate - Lesson 10: jQuery Copy, Data & Type Utilities

What's Next?

In the next lesson we take a look at the jQuery copy, data and type utility methods.