Open In App

How to reverse array of DOM elements using jQuery ?

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of DOM elements, the task is to reverse this array using jQuery. There are two approaches that can be taken to achieve this:

Approach 1: Use inbuilt jQuery methods such as get(), reverse(), and each(). Firstly, select all the required DOM elements using the get() method which returns a JavaScript array. Then, the native JavaScript method reverse() is used to reverse the array of DOM elements. Finally, each() method iterates over each DOM element of the reversed array.

Example: In this example, we will use the above approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <!-- jQuery -->
    <script src=
    </script>
    <title>
        Reverse array of DOM elements using jQuery
    </title>
     
    <!-- Basic inline styling -->
    <style>
        body {
            text-align: center;
        }
 
        p {
            font-weight: bold;
            font-size: 1.5rem;
        }
 
        h1 {
            color: green;
            font-size: 2.5rem;
        }
 
        button {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <p>Geek 1</p>
    <p>Geek 2</p>
    <p>Geek 3</p>
    <p>Geek 4</p>
    <p>Geek 5</p>
    <script type="text/javascript">
        $($("p").get().reverse()).each(function (i) {
            $(this).text("Geek " + ++i);
        });
    </script>
</body>
</html>


Output:

Approach 2: Using a small jQuery plugin. The plugin jQuery.fn.reverse = [].reverse can be used to reverse an array of DOM elements when coupled with each() method as discussed in the previous approach.

Example: In this example, we will use the above approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <!-- jQuery -->
    <script src=
    </script>
    <title>
        Reverse array of DOM elements using jQuery
    </title>  
    <!-- Basic inline styling -->
    <style>
        body {
            text-align: center;
        }
 
        p {
            font-weight: bold;
            font-size: 1.5rem;
        }
 
        h1 {
            color: green;
            font-size: 2.5rem;
        }
 
        button {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <p>Geek 1</p>
    <p>Geek 2</p>
    <p>Geek 3</p>
    <p>Geek 4</p>
    <p>Geek 5</p>
    <script type="text/javascript">
        $.fn.reverse = [].reverse;
        $("p").reverse().each(function (i) {
            $(this).text("Geek " + ++i);
        });
    </script>
</body>
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads