jquery
  1. jquery-chaining

jQuery Chaining

jQuery chaining is a technique in jQuery that allows you to perform multiple operations on a selected element in a single line of code. This can make your code more concise and easier to read, and can also improve performance by reducing the number of times your code needs to traverse the DOM.

Syntax

jQuery chaining involves calling multiple methods on a selected element, separated by a period. Here is an example syntax:

$(selector).method1().method2().method3();

Use

jQuery chaining is useful for performing multiple operations on a selected element, such as setting and getting CSS properties, adding or removing classes, or manipulating the DOM. By chaining these operations together in a single line of code, you can create more efficient and organized code.

Example

Here is an example of using jQuery chaining to set the background color and font color of a div element, and then add a class to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Chaining Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: lightblue;
            margin: 10px;
        }
    </style>
</head>
<body>
    <div id="box1"></div>
    <div id="box2"></div>

    <script>
        // Use $(document).ready() to ensure the DOM is fully loaded before executing the script
        $(document).ready(function() {
            // jQuery chaining example
            $("#box1")
                .css("border", "2px solid blue")
                .fadeOut(2000)
                .fadeIn(2000)
                .slideUp(1000)
                .slideDown(1000);
            
            // Another example with different element
            $("#box2")
                .css("border", "2px solid red")
                .fadeOut(1500)
                .fadeIn(1500)
                .slideUp(800)
                .slideDown(800);
        });
    </script>
</body>
</html>
Try Playground

In this example, we select all div elements on the page and then use jQuery chaining to set their background color to yellow, font color to blue, and add a class called "border" to each of them.

Summary

jQuery chaining is a powerful technique that allows you to perform multiple operations on a selected element in a single line of code. It can make your code more concise, easier to read, and more efficient. Use jQuery chaining to improve your coding skills and create more effective web applications.

Published on: