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

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

Ordering DIVs based on class name using Javascript/Jquery

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...