3

I have the following:

<div>
    <div>
        <span>Fe</span>
        <span>Fi</span>
        <span>Fo</span>
        <span>Fum</span>
    </div>


    <div>
        <span>He</span>
        <span>Hi</span>
        <span>Ho</span>
        <span>Hum</span>
    </div>
</div>

And I would like the inner divs to display in reverse order like so:

He Hi Ho Hum
Fee Fi Fo Fum

3
  • You're example result doesn't really reverse the sort order. It just swaps the order of the two <div> elements. Is that what you want? Commented May 19, 2011 at 17:45
  • @Patrick: Yes, that is what I'm trying to accomplish Commented May 19, 2011 at 17:47
  • Alright, I posted an answer that does that. Commented May 19, 2011 at 17:48

6 Answers 6

8
var first = $('div > div:first-child');

first.appendTo(first.parent());

EDIT: To deal with several elements, you can do this:

$('div > div').each(function() {
    $(this).prependTo(this.parentNode);
});

Live Example: http://jsfiddle.net/xB4sB/

Sign up to request clarification or add additional context in comments.

3 Comments

This is the simplest and most generic version offered. Thanks!
Can this be generalized even further so that if there were 3 or 4 divs that they would be listed in reverse order?
@user113716 Do you know if this will work with ordered list elements, without changing their numeric value?
2

One method is:

$('div span:contains("He")').parent().insertBefore('div > div:eq(0)');

JS Fiddle demo.

Conversely, you could also just CSS to simulate the 'reversed' order:

div > div {
    width: 48%;
    float: right;
}

div > div:nth-child(odd) {
    background-color: #ffa;
}

div > div:nth-child(even) {
    background-color: #0f0;
}

JS Fiddle demo.

References:

2 Comments

Your jQuery solution works visually, but I'm pretty sure OP wants to keep them in the same outer div. Currently it is placing it outside the outer. You'd need to change the selector to .insertBefore('div:eq(1)') or .insertBefore('div > div:eq(0)') or use .prependTo('div:eq(0)').
@patrick dw: thanks! That's what I meant to do, but completely forgot that they were contained...sigh. Must read more slowly and carefully... edited
1

You could swap the two nodes using this method. Here's a live demo. Also you probably could give them unique id names to simplify the selectors.

Comments

0

jQuery Sortable to the rescue.

Comments

0

Try something like this:

$($("span").remove().toArray().reverse()).appendTo("div");

Comments

0

give each div an id and use insertBefore. Example:

$('#hehihohum').insertBefore('#fefifofum');

jsFiddle

1 Comment

I like your avatar, Home Movies is fantastic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.