How can I sort elements by numerical value of data attribute?
Use Array.sort
:
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +a.dataset.percentage - +b.dataset.percentage;
})
.appendTo($wrapper);
Here's the fiddle: http://jsfiddle.net/UdvDD/
If you're using IE < 10, you can't use the dataset
property. Use getAttribute
instead:
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +a.getAttribute('data-percentage') - +b.getAttribute('data-percentage');
})
.appendTo($wrapper);
Here's the fiddle: http://jsfiddle.net/UdvDD/1/
Sort HTML elements by data-attribute
You should use Array#sort
, just pass it a function that checks the data-category-group
property (using String#localeCompare()
):
var categoryItems = document.querySelectorAll("[data-category-group]");
var categoryItemsArray = Array.from(categoryItems);
let sorted = categoryItemsArray.sort(sorter);
function sorter(a,b) {
return a.dataset.categoryGroup.localeCompare(b.dataset.categoryGroup); // sorts based on alphabetical order
}
document.querySelector("button").onclick = () => sorted.forEach(e => document.querySelector("#demo").appendChild(e));
<ul id="demo">
<li class="category-item" data-category-group="jeans">Bottoms</li>
<li class="category-item" data-category-group="tops">Shirt</li>
<li class="category-item" data-category-group="jeans">Jeans</li>
<li class="category-item" data-category-group="jeans">Shorts</li>
<li class="category-item" data-category-group="tops">Hoodie</li>
<li class="category-item" data-category-group="accesories">Sunglasses</li>
</ul>
<button>Sort Elements</button>
Sorting a list by data-attribute
This works for any number of lists: it basically gathers all li
s in ul
s that have your attribute, sorts them according to their data-*
attribute value and re-appends them to their parent.
Array.from(document.querySelectorAll("ul > li[data-azsort]"))
.sort(({dataset: {azsort: a}}, {dataset: {azsort: b}}) => a.localeCompare(b)) // To reverse it, use `b.localeCompare(a)`.
.forEach((item) => item.parentNode.appendChild(item));
<ul>
<li data-azsort="skeetjon">
<a href="#"><span class="list-name">Jon Skeet</span></a>
<span class="list-desc">Stack Overflow user</span>
</li>
<li data-azsort="smithjohn">
<a href="#"><span class="list-name">John Smith</span></a>
<span class="list-desc">Professor</span>
</li>
<li data-azsort="barnestom">
<a href="#"><span class="list-name">Tom Barnes</span></a>
<span class="list-desc">Lecturer</span>
</li>
</ul>
<ul>
<li data-azsort="smithjohn">
<a href="#"><span class="list-name">John Smith</span></a>
<span class="list-desc">Professor</span>
</li>
<li data-azsort="barnestom">
<a href="#"><span class="list-name">Tom Barnes</span></a>
<span class="list-desc">Lecturer</span>
</li>
<li data-azsort="skeetjon">
<a href="#"><span class="list-name">Jon Skeet</span></a>
<span class="list-desc">Stack Overflow user</span>
</li>
</ul>
How to sort out elements by their value in data- attribute using JS
You need to append them to the DOM in the newly sorted order.
Here's what I added to your code to do this:
divs.sort(function(a, b) {
return a.dataset.val.localeCompare(b.dataset.val);
});
var br = document.getElementsByTagName("br")[0];
divs.forEach(function(el) {
document.body.insertBefore(el, br);
});
http://jsfiddle.net/RZ2K4/
The appendChild()
method could be used instead of .insertBefore()
if your sorted items were in a container with nothing else.
To support older browsers, you would use .getAttribute("data-val")
instead of .dataset.val
.
And if you want a numeric sorting, you shouldn't use .localeCompare
in the .sort()
function.
jQuery sort order by data attribute
A few things:
sort
should not return a boolean, but rather a negative, positive, or zero*:if (a < b) return -1; //negative
if (a > b) return 1; //positive
if (a === b) return 0; //0Easier expressed as:
return a - b;
You can use
appendTo()
in place of.each( .append() )
, which I'd expect to perform slightly better..attr("data-order")
can be expressed as.data("order")
(though this is more a matter of preference).
$(".list a") .sort((a,b) => $(a).data("order") - $(b).data("order")) .appendTo(".list");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="list"> <a href="#" data-order="4">Thing 4</a> <a href="#" data-order="3">Thing 3</a> <a href="#" data-order="1">Thing 1</a> <a href="#" data-order="2">Thing 2</a></div>
Sorting list items by data attribute, alphabetically and then numerically
ASCII codes of digits are smaller than alphabets, so just simply add weight to them when doing comparison like this:
$(".columns li").sort(sort_li).appendTo('.columns');
function sort_li(a, b){
var va = $(a).data('char').toString().charCodeAt(0);
var vb = $(b).data('char').toString().charCodeAt(0);
if (va < 'a'.charCodeAt(0)) va += 100; // Add weight if it's a number
if (vb < 'a'.charCodeAt(0)) vb += 100; // Add weight if it's a number
return vb < va ? 1 : -1;
}
Updated JSFiddle here
Javascript/jQuery: Reordering divs according to data-attribute values
Here is the solution
HTML:
<div id="list">
<div class="listing-item" data-listing-price="2">2</div>
<div class="listing-item" data-listing-price="3">3</div>
<div class="listing-item" data-listing-price="1">1</div>
<div class="listing-item" data-listing-price="4">4</div>
</div>
JS:
var divList = $(".listing-item");
divList.sort(function(a, b){
return $(a).data("listing-price")-$(b).data("listing-price")
});
$("#list").html(divList);
JSFiddle:
http://jsfiddle.net/bittu4u4ever/ezYJh/1/
How to sort div order position by data-attribute
You're using the this
keyword in the sort()
handler whereas you instead need to use the a
and b
element references in order to compare them. You can also use data()
instead of attr()
to return the attributes. This will also return an integer to negate the need for parseInt()
. Once the elements are sorted you can just append()
them to the container without the extra each()
loop. Try this:
$("#bout div.foot").sort(function(a, b) {
return $(a).data("position") - $(b).data("position");
}).appendTo("#bout");
// alternative #1
// $("#bout div.foot").sort((a, b) => $(a).data("position") - $(b).data("position")).appendTo("#bout");
// alternative #2
// $("#bout div.foot").sort((a, b) => a.dataset.position - b.dataset.position).appendTo("#bout");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container vendors" id="bout">
<div class="col-md-6 foot" data-position="4">4</div>
<div class="col-md-6 foot" data-position="3">3</div>
<div class="col-md-6 foot" data-position="4">4</div>
<div class="col-md-6 foot" data-position="1">1</div>
</div>
jquery sort list based on data attribute value
Try to use sort()
with appendTo()
,
$(".listitems li").sort(sort_li) // sort elements
.appendTo('.listitems'); // append again to the list
// sort function callback
function sort_li(a, b){
return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
}
Snippet:
$(function() {
$(".listitems li").sort(sort_li).appendTo('.listitems');
function sort_li(a, b) {
return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="listitems">
<li data-position="3">Item 3</li>
<li data-position="2">Item 2</li>
<li data-position="1">Item 1</li>
<li data-position="4">Item 4</li>
</ul>
Related Topics
Access Event to Call Preventdefault from Custom Function Originating from Onclick Attribute of Tag
How to Determine If a Checkbox Is Checked
How to Implement Dynamic Getters/Setters in JavaScript
JavaScript Checking for Null VS. Undefined and Difference Between == and ===
How Does the New Operator Work in JavaScript
Array VS. Object Efficiency in JavaScript
JavaScript Require() Function Giving Referenceerror: Require Is Not Defined
Redirect Parent Window from an Iframe Action
Are All JavaScript Callbacks Asynchronous? If Not, How to Know Which Are
How to Prevent Page from Reloading After Form Submit - Jquery
How to Get Image from Canvas Element and Use It in Img Src Tag
Template Does Not Update When Using Ui-Router and Ion-Tabs
Chrome Autofill/Autocomplete No Value for Password
Html5 - Cross Browser Iframe Postmessage - Child to Parent