开发者

Reverse sort divs using CSS or jQuery?

I h开发者_如何学JAVAave 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


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/


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:

  • :contains-selector().
  • parent().
  • insertBefore().
  • eq().


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.


jQuery Sortable to the rescue.


Try something like this:

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


give each div an id and use insertBefore. Example:

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

jsFiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜