0

I have the below HTML which is displayed via jQuery, it is a list of users - but I am trying to find a way to specify an id name which makes the appropriate my_list div move to the top of the order?

Example:

<div class="my_list" id="peter"><label class="name">Peter - <div id="peter_status"></div></label></div>
<div class="my_list" id="sam"><label class="name">Sam - <div id="sam_status"></div></label></div>
<div class="my_list" id="derek"><label class="name">Derek - <div id="derek_status"></div></label></div>

Would turn into the following if I was to specify Sam:

<div class="my_list" id="sam"><label class="name">Sam - <div id="sam_status"></div></label></div>
<div class="my_list" id="peter"><label class="name">Peter - <div id="peter_status"></div></label></div>
<div class="my_list" id="derek"><label class="name">Derek - <div id="derek_status"></div></label></div>

My attempt at creating some code to assist is below:

$( '<div class="my_list" id="sam">' ).insertBefore($( ".my_list" ).first());
GillesC
  • 10,647
  • 3
  • 40
  • 55
Stone
  • 343
  • 1
  • 5
  • 11
  • 1
    So just prepend the element with the given id to the top? `$('#sam').parent().prepend($('#sam'))` – adeneo Oct 23 '15 at 21:16

3 Answers3

0

Here are some related answers, found by Googling "javascript rearrange div order":

Community
  • 1
  • 1
Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
  • 1
    This is more of a comment than an actual answer... Why not flag it as duplicate of one of them? – Mike Oct 23 '15 at 21:24
0

Try this JSFiddle demo.

Note that we need a container for your divs to sort:

<div class="container">
    <div class="my_list" id="peter">
        <label class="name">Peter -
            <div id="peter_status"></div>
        </label>
    </div>
    <div class="my_list" id="sam">
        <label class="name">Sam -
            <div id="sam_status"></div>
        </label>
    </div>
    <div class="my_list" id="derek">
        <label class="name">Derek -
            <div id="derek_status"></div>
        </label>
    </div>
</div>

And this JS code does the trick by using the remove() and prepend() jQuery methods:

var divId = 'sam';
$('button.sort-divs').on('click', function () {
    var divHtml = $('#' + divId).html();
    $('#' + divId).remove();
    $('.container').prepend(divHtml);
});
leo.fcx
  • 6,137
  • 2
  • 21
  • 37
0

You don't need much of code. Given every element you need to sort has its own id, you can use this code, easy and scalable:

var order = ['sam','peter','derek'];
for (var i = 1; i < order.length; i++) {
    $('#'+order[i]).insertAfter('#'+order[i-1]);
}

Here you have a JsFiddle.

Kar.ma
  • 743
  • 6
  • 12