jQuery reorder list items based on class
Asked Answered
R

2

7

Is there a simple way to reorder my list items using a class?

I want to specify a class to feature those items at the top of the list first, with other list items listed below.

<ul class="order-me">
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
</ul>

Desired output:

<ul class="order-me">
    <li class="featured">featured content</li>
    <li class="featured">featured content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
    <li class="">normal content</li>
</ul>

Thanks!

Rubiaceous answered 12/9, 2014 at 9:12 Comment(0)
H
13

You can prepend the .featured elements to their containing ul to move them to the top of the list. Try this:

$('.featured').prependTo('.order-me');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="order-me">
  <li class="">normal content</li>
  <li class="">normal content</li>
  <li class="featured">featured content</li>
  <li class="">normal content</li>
  <li class="featured">featured content</li>
  <li class="">normal content</li>
  <li class="">normal content</li>
</ul>
Hauser answered 12/9, 2014 at 9:13 Comment(2)
Wow, suck me sideways that was easier than I thought. Thank you Rory!Rubiaceous
jQuery usually is :D Glad to help.Hauser
C
1

To add to @Rory McCrossan's answer, I've added the ability to sort it with navigation buttons

$("ul.order-nav li").click(function() {
  // Find the Data attribute from unordered list [.order-nav]
  var sortClass = '.' + $(this).data('sort-by');
  // Prepent the [li] with matching class to top of [ul]
  $(sortClass).prependTo('.order-me');
});

Here is the Fiddle

Calcic answered 29/4, 2016 at 7:14 Comment(1)
Late to the party, but a nice addition, I like it. Cheers.Rubiaceous

© 2022 - 2024 — McMap. All rights reserved.