Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following HTML structure:

<div id="container">
    <div>1</div>
    <div class="red">2</div>
    <div class="red">3</div>
    <div>4</div>
    <div>5</div>
    <div class="red">6</div>
    <div>7</div>
</div>

I wast to run some Jquery that will sort the divs inside the div container by ordering the divs first that have class="red", and then those that don't, so the final structure should be:

<div id="container">
    <div class="red">2</div>
    <div class="red">3</div>
    <div class="red">6</div>
    <div>1</div>
    <div>4</div>
    <div>5</div>
    <div>7</div>
</div>

Help? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
820 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

 $(function(){
   var elem = $('#container').find('div').sort(sortMe);
   $('#container').append(elem);
 });

 function sortMe(a, b) {
        return a.className < b.className;
  }

Demo

With Some fadeIn/fadeout animation

var elem = $('#container').find('div').sort(sortByClass);

 function sortByClass(a, b) {
    return a.className < b.className;
 }

 var allElem = elem.get();
  (function append() {

    var $this = $(allElem.shift());

     $('#container').append(
                $this.fadeOut('slow'))
                         .find($this)
                             .fadeIn('slow', function () {
                                      if (allElem.length > 0) 
                                          window.setTimeout(append);
                            });
      })();

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...