"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > jQuery.each() reverse traversal element method

jQuery.each() reverse traversal element method

Posted on 2025-04-15
Browse:191

How to Iterate Through Elements in Reverse Order with jQuery\'s .each()?

Iterating Elements Backwards with JQuery's .each()

In situations where you need to traverse elements in the reverse order in the DOM, JQuery's default .each() function may not suffice. Consider the following HTML:

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

To select all the li elements and iterate them backward, we can use the following approach:

$.($("li").get().reverse()).each(function() { /* ... */ });

Here's how it works:

  1. Select the li elements: $("li").
  2. Convert the result to a native array: get() returns the elements as an array.
  3. Reverse the array: reverse() creates a new array with the elements in reverse order.
  4. Wrap the reversed array back in a jQuery object: $() allows us to use JQuery functions on the reversed array.
  5. Apply the .each() function to iterate the elements in reverse order.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3