0

Unfortunately, I could not solve that myself. I have a list with several DIV which ALWAYS have the same ID and class. The list I sort according to the "data-sort" attributes and it works wonderfully.

Currently it looks like this:

<div id="divList">

<div id="hsdf" data-sort="1"></div>
<div class="hsdf" data-sort="1"></div>

<div class="vasfd" data-sort="2"></div>
<div id="vasfd" data-sort="2"></div>

<div id="asdfas" data-sort="3"></div>
<div class="asdfas" data-sort="3"></div>

</div>

I would like however in the list sorting first the class and then the ID comes. Like here:

<div id="divList">

<div class="hsdf" data-sort="1"></div>
<div id="hsdf" data-sort="1"></div>

<div class="vasfd" data-sort="2"></div>
<div id="vasfd" data-sort="2"></div>

<div class="asdfas" data-sort="3"></div>
<div id="asdfas" data-sort="3"></div>

</div>

The "data-sort" attribute sorting is done with the jQuery:

jQuery('#divList').find('div').sort(function (a, b) {
return jQuery(a).attr('data-sort') - jQuery(b).attr('data-sort');
}).appendTo('#divList');

Do you have any ideas for me?

2 Answers 2

1

You can use this in your sort function:

return jQuery(a).attr('data-sort') - jQuery(b).attr('data-sort')
  || !!jQuery(a).attr("id") - !!jQuery(a).attr("class");

This checks for the existence of an id and for a class. If the class exists, the expression after || will evalutate to -1, if the ID exists, it will evalutate to 1. This will be relevant if the expression before || evaluates to 0 (when they have the same data-sort value).

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

2 Comments

Thanks, so it worked. "B" instead of "A" ` return jQuery(a).attr('data-sort') - jQuery(b).attr('data-sort') || !jQuery(b).attr('id') - !jQuery(b).attr('class');`
@od_ Those are equivalent. The sorting function compares a and b. My approach sorts a first, if it has a class, your approach sorts b last, if it has an ID. In this scenario, it’s the same.
1

Something like this should work:

jQuery('#divList').find('div').sort(function (a, b) {
    var diff = jQuery(a).attr('data-sort') - jQuery(b).attr('data-sort');
    if (diff == 0) {
        if (jQuery(a).attr('class') && jQuery(a).attr('class') != '') {
            diff = -1;
        } else {
            diff = 1;
        }
    }
    return diff;
}).appendTo('#divList');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.