Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  32] [ 2]  / answers: 1 / hits: 25113  / 15 Years ago, wed, october 21, 2009, 12:00:00

I'm trying to re-sort the child elements of the tag input by comparing
their category attribute to the category order in the Javascript
variable category_sort_order. Then I need to remove divs whose category attribute
does not appear in category_sort_order.



The expected result should be:




any

product1

product2

download




The code:



<div id=input>
<div category=download>download</div>
<div category=video>video1</div>
<div category=video>video2</div>
<div category=product>product1</div>
<div category=any>any</div>
<div category=product>product2</div>
</div>

<script type=text/javascript>
var category_sort_order = ['any', 'product', 'download'];
</script>


I really don't even know where to begin with this task but if you could please provide any assistance whatsoever I would be extremely grateful.


More From » jquery

 Answers
48

I wrote a jQuery plugin to do this kind of thing that can be easily adapted for your use case.



The original plugin is here



Here's a revamp for you question



(function($) {

$.fn.reOrder = function(array) {
return this.each(function() {

if (array) {
for(var i=0; i < array.length; i++)
array[i] = $('div[category=' + array[i] + ']');

$(this).empty();

for(var i=0; i < array.length; i++)
$(this).append(array[i]);
}
});
}
})(jQuery);


and use like so



var category_sort_order = ['any', 'product', 'download'];
$('#input').reOrder(category_sort_order);


This happens to get the right order for the products this time as product1 appears before product2 in the original list, but it could be changed easily to sort categories first before putting into the array and appending to the DOM. Also, if using this for a number of elements, it could be improved by appending all elements in the array in one go instead of iterating over the array and appending one at a time. This would probably be a good case for DocumentFragments.


[#98470] Friday, October 16, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;