Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort <ul><li>'s based on class with javascript?

Tags:

javascript

I have a TODO list app with an Unordered list. Within it I have a few list items. The li classes are high,medium,low. I would like li's with the class high to be placed before li's with the class medium and last ones with low.

<ul id="tasks">
  <li id="item3" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item3')"></a><span>This is a low priority task</span></li>
  <li id="item4" class="priority high"><></span><a href="#" class="closex" onclick="removeItem('item4')"></a><span>This is a high priority task</span></li>
  <li id="item5" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item5')"></a><span>This is another Low</span></li>
  <li id="item7" class="priority medium"><span></span><a href="#" class="closex" onclick="removeItem('item7')"></a><span>And now a Medium</span></li>
</ul>

So the li with id of item4 should be first and then it should be item7 and then the li's with class low after.

like image 459
Bry Avatar asked Nov 03 '22 12:11

Bry


1 Answers

Here's a pure JS version of @ŠimeVidas jQuery solution.

var tasks = document.querySelector('#tasks'),
    items = document.querySelectorAll('#tasks > li');

for (var i = 0, arr = ['high', 'medium', 'low']; i < arr.length; i++) {
    for (var j = 0; j < items.length; j++) {
        if (~(" " + items[j].className + " ").indexOf(" " + arr[i] + " "))
            tasks.appendChild(items[j]);
    }
}
like image 183
I Hate Lazy Avatar answered Nov 12 '22 16:11

I Hate Lazy