jQuery & DOM Manipulation

jQuery Utilities & Helpers

12 min Lesson 29 of 30

jQuery Utilities & Helpers

jQuery provides a collection of utility functions that help you perform common tasks more efficiently. These functions are accessed directly through the $ or jQuery object and don't require a selector.

Array and Object Utilities

$.each() - Iterate Over Arrays and Objects

The $.each() function iterates over arrays and objects, executing a callback for each element.

<script>
// Iterating over an array
var fruits = ['apple', 'banana', 'orange'];

$.each(fruits, function(index, value) {
    console.log(index + ': ' + value);
});
// Output: 0: apple, 1: banana, 2: orange

// Iterating over an object
var person = {
    name: 'John',
    age: 30,
    city: 'New York'
};

$.each(person, function(key, value) {
    console.log(key + ': ' + value);
});
// Output: name: John, age: 30, city: New York

// Practical example: Populating a list
var colors = ['red', 'green', 'blue'];
var list = $('<ul></ul>');

$.each(colors, function(i, color) {
    list.append('<li>' + color + '</li>');
});

$('#color-container').append(list);
</script>

$.map() - Transform Array Elements

The $.map() function creates a new array with the results of calling a function on every element.

<script>
// Transforming an array
var numbers = [1, 2, 3, 4, 5];

var doubled = $.map(numbers, function(value) {
    return value * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]

// Extracting properties from objects
var users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 },
    { name: 'Bob', age: 35 }
];

var names = $.map(users, function(user) {
    return user.name;
});

console.log(names); // ['John', 'Jane', 'Bob']

// Filtering and mapping combined
var products = [
    { name: 'Laptop', price: 1000 },
    { name: 'Mouse', price: 25 },
    { name: 'Keyboard', price: 75 }
];

var expensiveItems = $.map(products, function(product) {
    if (product.price > 50) {
        return product.name;
    }
});

console.log(expensiveItems); // ['Laptop', 'Keyboard']
</script>

$.grep() - Filter Array Elements

The $.grep() function filters an array based on a condition.

<script>
// Filtering numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var evenNumbers = $.grep(numbers, function(n) {
    return n % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6, 8, 10]

// Filtering with invert option
var oddNumbers = $.grep(numbers, function(n) {
    return n % 2 === 0;
}, true); // true inverts the filter

console.log(oddNumbers); // [1, 3, 5, 7, 9]

// Practical example: Filter completed tasks
var tasks = [
    { title: 'Buy groceries', completed: true },
    { title: 'Write report', completed: false },
    { title: 'Call client', completed: true },
    { title: 'Review code', completed: false }
];

var completedTasks = $.grep(tasks, function(task) {
    return task.completed;
});

console.log(completedTasks.length + ' tasks completed');
</script>

String Utilities

$.trim() - Remove Whitespace

The $.trim() function removes leading and trailing whitespace from a string.

<script>
var text = '   Hello World   ';
var trimmed = $.trim(text);

console.log('|' + text + '|');     // |   Hello World   |
console.log('|' + trimmed + '|'); // |Hello World|

// Practical example: Clean user input
$('#submit-btn').click(function() {
    var username = $.trim($('#username').val());
    var email = $.trim($('#email').val());

    if (username === '') {
        alert('Username cannot be empty');
        return false;
    }

    // Process cleaned data
    console.log('Username: ' + username);
    console.log('Email: ' + email);
});
</script>
Tip: While modern browsers support String.trim(), $.trim() ensures compatibility with older browsers.

Array Search Utilities

$.inArray() - Find Element Index

The $.inArray() function searches for a value in an array and returns its index (or -1 if not found).

<script>
var fruits = ['apple', 'banana', 'orange', 'grape'];

console.log($.inArray('banana', fruits));  // 1
console.log($.inArray('mango', fruits));   // -1

// Practical example: Check if item exists
var selectedItems = ['item1', 'item3', 'item5'];

$('#add-item-btn').click(function() {
    var itemId = $(this).data('item-id');

    if ($.inArray(itemId, selectedItems) === -1) {
        selectedItems.push(itemId);
        console.log('Item added');
    } else {
        console.log('Item already selected');
    }
});

// Check multiple values
function hasAnyFruit(fruits) {
    var searchFor = ['apple', 'pear'];

    for (var i = 0; i < searchFor.length; i++) {
        if ($.inArray(searchFor[i], fruits) !== -1) {
            return true;
        }
    }
    return false;
}

console.log(hasAnyFruit(fruits)); // true
</script>

Type Checking Utilities

jQuery provides several functions to check variable types.

<script>
// $.isArray() - Check if variable is an array
console.log($.isArray([1, 2, 3]));     // true
console.log($.isArray('string'));      // false

// $.isFunction() - Check if variable is a function
console.log($.isFunction(function(){})); // true
console.log($.isFunction(123));          // false

// $.isNumeric() - Check if variable is numeric
console.log($.isNumeric(123));      // true
console.log($.isNumeric('123'));    // true
console.log($.isNumeric('abc'));    // false

// $.isPlainObject() - Check if variable is a plain object
console.log($.isPlainObject({}));                // true
console.log($.isPlainObject({a: 1}));            // true
console.log($.isPlainObject(new Date()));        // false
console.log($.isPlainObject([1, 2]));            // false

// $.isEmptyObject() - Check if object has no properties
console.log($.isEmptyObject({}));           // true
console.log($.isEmptyObject({a: 1}));       // false

// Practical example: Validate data before AJAX
function sendData(data) {
    if (!$.isPlainObject(data)) {
        console.error('Data must be an object');
        return;
    }

    if ($.isEmptyObject(data)) {
        console.error('Data cannot be empty');
        return;
    }

    // Send data
    $.ajax({
        url: '/api/save',
        method: 'POST',
        data: data
    });
}
</script>

Object Manipulation

$.extend() - Merge Objects

The $.extend() function merges the contents of two or more objects together.

<script>
// Basic merge
var defaults = {
    color: 'blue',
    size: 'medium',
    price: 100
};

var options = {
    color: 'red',
    discount: 10
};

var settings = $.extend({}, defaults, options);

console.log(settings);
// { color: 'red', size: 'medium', price: 100, discount: 10 }

// Deep merge
var obj1 = {
    a: 1,
    b: {
        c: 2,
        d: 3
    }
};

var obj2 = {
    b: {
        d: 4,
        e: 5
    },
    f: 6
};

var merged = $.extend(true, {}, obj1, obj2); // true = deep merge

console.log(merged);
// { a: 1, b: { c: 2, d: 4, e: 5 }, f: 6 }

// Practical example: Plugin configuration
function MyPlugin(element, options) {
    this.settings = $.extend({}, MyPlugin.defaults, options);
    this.element = $(element);
    this.init();
}

MyPlugin.defaults = {
    speed: 300,
    effect: 'fade',
    autoplay: false
};

MyPlugin.prototype.init = function() {
    console.log('Plugin initialized with:', this.settings);
};

// Usage
var plugin = new MyPlugin('#my-element', {
    speed: 500,
    autoplay: true
});
</script>

Parsing Utilities

$.parseJSON() and $.parseHTML()

<script>
// $.parseJSON() - Parse JSON string
var jsonString = '{"name":"John","age":30}';
var obj = $.parseJSON(jsonString);

console.log(obj.name); // John
console.log(obj.age);  // 30

// $.parseHTML() - Parse HTML string into DOM nodes
var htmlString = '<div class="box"><p>Hello</p></div>';
var nodes = $.parseHTML(htmlString);

$('#container').append(nodes);

// Practical example: Process API response
$.ajax({
    url: '/api/user',
    dataType: 'text', // Receive as text
    success: function(response) {
        try {
            var data = $.parseJSON(response);
            displayUser(data);
        } catch (e) {
            console.error('Invalid JSON response');
        }
    }
});
</script>
Note: In modern jQuery, you can use native JSON.parse() instead of $.parseJSON(), but jQuery's version provides better error handling for older browsers.

Miscellaneous Utilities

$.now() - Get Current Timestamp

<script>
// Get current timestamp in milliseconds
var timestamp = $.now();
console.log(timestamp); // e.g., 1635789456789

// Practical example: Measure performance
var startTime = $.now();

// Perform some operation
for (var i = 0; i < 1000000; i++) {
    // Some work
}

var endTime = $.now();
var duration = endTime - startTime;

console.log('Operation took ' + duration + 'ms');

// Cache busting
function loadData() {
    $.ajax({
        url: '/api/data?t=' + $.now(), // Prevent caching
        success: function(data) {
            console.log(data);
        }
    });
}
</script>

$.noop() - Empty Function

A empty function that can be used as a placeholder.

<script>
// Using $.noop() as a default callback
function processData(data, callback) {
    callback = callback || $.noop;

    // Process data
    console.log('Processing...');

    // Execute callback
    callback();
}

// Call without callback - no error
processData({name: 'John'});

// Call with callback
processData({name: 'Jane'}, function() {
    console.log('Done!');
});
</script>

Practice Exercise

Task: Create a data processing utility that uses multiple jQuery utilities.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Utilities Exercise</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .results {
            background: var(--bg-light);
            padding: 15px;
            margin-top: 10px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>Data Processing Utility</h1>

    <button id="process-btn">Process Data</button>
    <div id="results" class="results"></div>

    <script>
        $(document).ready(function() {
            var users = [
                { name: '  John Doe  ', age: 25, active: true },
                { name: 'Jane Smith', age: 30, active: false },
                { name: '  Bob Johnson  ', age: 35, active: true },
                { name: 'Alice Brown', age: 28, active: true }
            ];

            $('#process-btn').click(function() {
                var startTime = $.now();

                // Clean names using $.map and $.trim
                var cleanedUsers = $.map(users, function(user) {
                    return $.extend({}, user, {
                        name: $.trim(user.name)
                    });
                });

                // Filter active users using $.grep
                var activeUsers = $.grep(cleanedUsers, function(user) {
                    return user.active;
                });

                // Get names of active users
                var activeNames = $.map(activeUsers, function(user) {
                    return user.name;
                });

                // Calculate average age
                var totalAge = 0;
                $.each(activeUsers, function(i, user) {
                    totalAge += user.age;
                });
                var avgAge = totalAge / activeUsers.length;

                var endTime = $.now();

                // Display results
                var html = '<h3>Results:</h3>';
                html += '<p>Active Users: ' + activeNames.join(', ') + '</p>';
                html += '<p>Average Age: ' + avgAge.toFixed(1) + '</p>';
                html += '<p>Processing Time: ' + (endTime - startTime) + 'ms</p>';

                $('#results').html(html);
            });
        });
    </script>
</body>
</html>

Summary

jQuery utilities provide powerful helpers for common programming tasks:

  • Array/Object: $.each(), $.map(), $.grep(), $.extend()
  • String: $.trim()
  • Search: $.inArray()
  • Type Checking: $.isArray(), $.isFunction(), $.isNumeric(), $.isPlainObject(), $.isEmptyObject()
  • Parsing: $.parseJSON(), $.parseHTML()
  • Miscellaneous: $.now(), $.noop()

These utilities make your code more concise, readable, and cross-browser compatible. In the next lesson, we'll explore jQuery best practices and build a complete real-world project!