0

Suppose I have HTML elements like below

<span class="active" data-id="3"> Test 3 </span>
<span class="active" data-id="1"> Test 1 </span>
<span class="active" data-id="2"> Test 2 </span>


$(".active"].each(function(index,item){
var val = $(item).data("id");
console.log(val);
});

This will output

3
1
2

Is there anyway we can sort this loop based on data attribute and get the elements by the order or Data attribute or some other way so it will output

1
2
3

Thank you.

Azer8
  • 539
  • 8
  • 18
Gracie williams
  • 1,287
  • 2
  • 16
  • 39
  • 2
    Duplicate of [Sorting a list by data-attribute](/q/32199368/4642212). Just replace the sort function by `({dataset: {id: a}}, {dataset: {id: b}}) => Number(a) - Number(b)`. – Sebastian Simon May 23 '21 at 16:23

1 Answers1

1

You need to use the ´sort´ higher order array method. Sort MDN Reference

const elements = Array.from(document.querySelectorAll('[data-id]'))

const sorted = elements.sort((firstEle, secondEle) => {
    const firstId = firstEle.dataset.id
    const secondId = secondEle.dataset.id
    
    return firstId > secondId
})


console.log(sorted)
violet
  • 91
  • 1
  • 4