I am trying to sort DOM based on a data-* attribute. The DOM looks like this, albeit repeated and with incrementing ids and different image source:
<div class="col mb-3" data-id="1" data-filter="Owned">
<div class="card template">
<img class="card-img w-100 d-block shadow" alt="Default Template" src="abc.jpg">
<div class="card-img-overlay">
<a class="btn btn-dark btn-sm template-preview float-end" role="button" target="_blank" href="organization.html/template.html?id=1">Preview</a>
</div>
<div class="card-body">
<h5 class="card-title">Default Template</h5>
<p class="card-text text-success">Owned</p>
</div>
</div>
</div>
I'm doing the sorting via a <select /> element where the <option /> values is a JSON literal that hold the field and direction, e.g.:
{
"field": "id",
"direction": "asc"
}
In the <select />'s change event, I have the following:
const templateSort_Change = (e) => {
const templateSort = e.currentTarget;
const templateSortValue = templateSort.value;
const sort = JSON.parse(templateSortValue);
const cols = document.querySelectorAll('div.col');
const sortedCols = Array.from(cols).sort((a, b) => {
if (sort.direction === 'desc') {
return a.dataset[sort.field].toLowerCase() - b.dataset[sort.field].toLowerCase();
} else {
return b.dataset[sort.field].toLowerCase() - a.dataset[sort.field].toLowerCase();
}
});
for (let col of cols) {
col.parentNode.appendChild(col);
}
}
The issue is that when it goes to do the for/of loop, the result of cols is the same order every time and looking at the documentation I'm not exactly sure why. I get that I'm doing string comparison, but these ids are still single digits (e.g. 1, 2, 3, etc.).
What am I doing wrong in my sort function that is causing the array to return the same order every time?