Assign background color in the DIV when sorting in alphabetical order in jQuery

1

Good evening!

I'm trying to build a list as follows:

<div>
  <div>id</div>
  <div><a id="orderStatus">status</a></div>
</div>
<div id="container">
  <div class="listStatus" style="background-color:#fff">
    <div>C</div>
    <div>1</div>
  </div>
  <div>
    <div class="listStatus" style="background-color:#DCDCDC">C</div>
    <div>2</div>
  </div>
  <div>
    <div class="listStatus" style="background-color:#FFF">A</div>
    <div>3</div>
  </div>
  <input type="hidden" id="acao" value="asc" />
</div>

The format that is printed is the same as a table, but with div's.

To make it easier to see the line, I created a line with background FFF and the other DCDCDC and so on, getting 'color yes, color not', but when I do the ordering, the colors order together making the functionality of the color miss the goal, which is to facilitate the visualization.

Is there a way to do color correction in the function below?

    $("#orderStatus").click(function(){
        var acao = $('#acao').val();
        var statusList = $(".listStatus");
        statusList.sort(function(a, b) {
            if(acao == "asc"){
                $('#acao').val('desc');
                var res = $(b).attr("status") > $(a).attr("status");
            }
            else{
                $('#acao').val('asc');
                var res = $(a).attr("status") > $(b).attr("status");
            }
            return res;

        });

        $('#container').html(statusList);
    });
    
asked by anonymous 08.11.2016 / 21:31

1 answer

1

I suggest doing this with CSS and taking the color logic out of HTML:

#container div div:nth-child(2n){
    	background-color: #dcdcdc;
    }
    
    #container div div:nth-child(2n + 1){
    	background-color: #fff;
    }
<div>
    <div>id</div>
    <div><a id="orderStatus">status</a></div>
</div>
<div id="container">
    <div class="listStatus">
        <div>C</div>
        <div>1</div>
    </div>
    <div>
        <div class="listStatus">C</div>
        <div>2</div>
    </div>
    <div>
        <div class="listStatus">A</div>
        <div>3</div>
    </div>
    <input type="hidden" id="acao" value="asc" />
</div>
    
08.11.2016 / 21:36