1

I want to sort the div elements in #list by class (cat1, cat2, cat3 etc...) using jQuery.

<section id="list" class="pix_wall pix_load_content isotope" style="position: relative; overflow: hidden; height: 570px; opacity: 1;">
<div class="cat8 entry post-id-34  isotope-item" data-sort="8" style="position: absolute; left: 0px; top: 0px;">
</div>
<div class="cat2 entry post-id-124  isotope-item" data-sort="2" style="position: absolute; left: 380px; top: 0px;">
</div>
<div class="cat7 entry post-id-79 isotope-item" data-sort="7" style="position: absolute; left: 760px; top: 0px;">
</div>
<div class="cat5 entry post-id-87 isotope-item" data-sort="5" style="position: absolute; left: 1140px; top: 0px;">
</div>
<div class="cat3 entry post-id-95 isotope-item" data-sort="3" style="position: absolute; left: 1520px; top: 0px;">
</div>
<div class="cat1 entry post-id-99 isotope-item" data-sort="1" style="position: absolute; left: 0px; top: 285px;">
</div>
</section>

Can anyone help me?

1

1 Answer 1

1
var sorted_entries = $('.entry').sort(function (a, b) { 
    var _a = /cat(\d+)/.exec(a.className)[1];
    var _b = /cat(\d+)/.exec(b.className)[1];

    if (_a < _b) {
        return -1;
    } else if (_a > _b) {
        return 1;
    } else {
        return 0;
    }
});

$('section').html(sorted_entries);

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

It would be better to move the elements around using appendTo instead of using the html() function as this removes events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.