Jose A.
Jose A.

Reputation: 125

Multiple ul reverse order

I'm new to jquery and I have a page with multiple unordered lists ul. I need to reverse order each ul, I saw this answer jQuery reversing the order of child elements but it messes all items with all lists. I tried to change the code to fit my needs but it doesn't do what I want, I can access each li of each ul but I don't know how to reverse the order of the li items.

My code:

$(function() {
  ul = $('ul'); // your parent element
  ul.each(function(i,ul){
     $(this).children().each(function (i,li) {
        alert(i);/*i got to do something here*/
     });
  })  
});

Upvotes: 3

Views: 1190

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074108

You can move elements around in the DOM quite easily, by inserting them either before or after other elements. When you get a set of elements in a jQuery instance (e.g., using $(...)), you get a static set of the elements that matched, in document order. So reversing them at that point is just a matter of looping through the matched set and moving them:

var list = $("selector_for_the_list");
var items = list.children();
var index;
for (index = items.length - 1; index >= 0; --index) {
    list.append(items[index]);
}

Live example

Upvotes: 1

Niklas
Niklas

Reputation: 13135

This is for when you have multiple ul's: http://jsfiddle.net/dG373/4/

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

-

$('ul').each(function(){
    var ul = $(this);
    ul.children().each(function(i, li){
        ul.prepend(li)
    });
});

Upvotes: 5

csharpnumpty
csharpnumpty

Reputation: 3723

Off the top of my head:

1.) select the items you wish to reverse the order of (e.g. $("div.myitems"))

2.) call $.makeArray on the items to turn into a true array.

3.) call the javascript .reverse() method to invert the array.

I've never done this so I'm not sure if it will work, but it might give you some ideas to build on!

Upvotes: 0

Related Questions