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/
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>
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/
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>
Sorting a div based on data attribute in jQuery
Sort the wrapper's divs
based on their data('worth')
, then append the sorted list back to the wrapper:
$('button').click(function() { $('.wrapper div').sort(function(a, b) { return $(b).data('worth') - $(a).data('worth'); }).appendTo('.wrapper');});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button>Sort</button><div class="wrapper"> <div class="item" data-worth="720">Edgy</div> <div class="item" data-worth="420">Blaze</div> <div class="item" data-worth="666">Meme</div></div>
Sorting Divs With JQuery Based On data- Attribute
your sort function have to return N or -N or 0 not a boolean:
let result = $("#tableEls .dataDiv").sort(function (a, b) {
console.log(+$(a).data("enter") + " - " + +$(b).data("enter"));
return +$(a).data("enter") - +$(b).data("enter");
}).appendTo("#tableEls");
console.log(result);
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>
jQuery sort function on dynamic data attribute
Use the .data()
Method since you sort by .data()
:
$.each(dataArr, function(i, obj) {
$('.store_item_' + obj.store_id).data('order', obj.store_order); // Update data
});
sortByShop_reOrder(); // sort by data
Example:
function sortByShop_reOrder() { $('#store_list .store_item').sort(function(a, b) { return $(a).data('order') - $(b).data('order'); }).appendTo('#store_list');}
function demoAJAX(dataArr) { $.each(dataArr, function(i, obj) { $('.store_item_' + obj.store_id).data('order', obj.store_order); }); sortByShop_reOrder()}
sortByShop_reOrder(); // do immediately and...setTimeout(function(){ // after 4 sec demoAJAX([ {"store_order":"1", "store_id":"11"}, {"store_order":"2", "store_id":"21"}, {"store_order":"3", "store_id":"22"} ])}, 4000);
<div id="store_list"> <div class="store_item store_item_11" data-order="2">2</div> <div class="store_item store_item_21" data-order="3">3</div> <div class="store_item store_item_22" data-order="1">1</div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related Topics
Differencebetween the Different Scroll Options
Unexpected JavaScript Date Behavior
How to Detect If a Variable Is an Array
Copy/Put Text on the Clipboard with Firefox, Safari and Chrome
Optimum Way to Compare Strings in JavaScript
React Router with Optional Path Parameter
Does JavaScript Support 64-Bit Integers
How to Maintain State After a Page Refresh in React.Js
Good Ways to Improve Jquery Selector Performance
Is There a Good JavaScript Minifier
Migrating Angularjs to Angular 4,5 (With Demo)
Count Number of Matches of a Regex in JavaScript
Javascript/Jquery: Test If Window Has Focus
Bootstrap 4 Multiselect Dropdown
Force Page Zoom at 100% with Js
What Tag in HTML Should I Use Without Special Meaning, Only to Carry Meta Data