JQuery class-based override list items

Is there an easy way to reorder list items using a class?

I want to specify a class to first include these items at the top of the list, as well as the 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 conclusion:

 <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!

+5
source share
2 answers

You can add .featured elements to their ul content to move them to the top of the list. Try the following:

 $('.featured').prependTo('.order-me'); 

Script example

+9
source

To add @Rory McCrossan to the answer, I added the ability to sort using the 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 script

+1
source

Source: https://habr.com/ru/post/1202408/


All Articles