Sometimes, we want to sort divs in JavaScript based on data-sort attribute values.
In this article, we’ll look at how to sort divs in JavaScript based on data-sort attribute values.
Sort Divs in JavaScript Based on data-sort Attribute Value
To sort divs in JavaScript based on data-sort attribute values, we can use the JavaScript array sort
method to sort the elements based on the data-sort
attribute value.
For instance, if we have the following HTML:
<section>
<div data-sort='12'>div12</div>
<div data-sort='4'>div4</div>
<div data-sort='19'>div19</div>
<div data-sort='1'>div1</div>
<div data-sort='8'>div8</div>
</section>
Then we can display the divs in the order of their data-sort
attribute values by writing:
const result = [...$('div')].sort((a, b) => {
const contentA = parseInt($(a).data('sort'));
const contentB = parseInt($(b).data('sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
$('section').html(result);
We select the divs with $
and convert the nodelist to an array with the spread operator.
Then we call sort
on the array with a callback that gets the data-sort
attribute value of element a
and b
with:
$(a).data('sort')
and
$(b).data('sort')
Then we call parseInt
to parse the values into integers.
Then we return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
to sort the elements in ascending order of their data-sort
attribute values.
And finally, we put the sorted divs into the section
element with:
$('section').html(result);
Now we should see:
div1
div4
div8
div12
div19
displayed.
Conclusion
To sort divs in JavaScript based on data-sort attribute values, we can use the JavaScript array sort
method to sort the elements based on the data-sort
attribute value.