Skip to content
Related Articles
Open in App
Not now

Related Articles

How to reverse array of DOM elements using jQuery ?

Improve Article
Save Article
  • Last Updated : 12 Feb, 2022
Improve Article
Save Article

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: Using 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 DOM elements. Finally, each() method iterates over each DOM element of the reversed array.

Example:

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 the each() method as discussed in the previous approach.

Example:

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:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!