I have a list of books in HTML, which contains multiple elements:
- The book's title
- The author's name
- Whether the book is finished or not (Completed / Ongoing)
- The book's synopsis
I am trying to make a button that would allow me to sort the list by whether a book is Completed or Ongoing. Additionally, I would like the list to be alphabetically sorted by title (so that, in the end, all the completed books appear at the top, in alphabetical order).
Another thing I'd like to accomplish is to have the list be sorted in ascending order in priority, and then, if the list is already in ascending order, have it sorted in descending order instead. This isn't super important, but it would be nice to have.
This all needs to be in pure javascript due to reasons outside my control :(
Unfortunately, I'm having no luck so far. Here's the code I have right now:
HTML:
<button class="button-9" onclick="sortByCompleted()">Sort by Completed</button>
<ul class="links-list" id="id01">
<li>
<a class="is-external-link" href="www.google.com">TITLE 1<span class="author" style="color:black">by AUTHOR1</span><span class="badge">Ongoing</span>
<em>Synopsis 1</em>
</a>
</li>
<li>
<a class="is-external-link" href="www.twitter.com">TITLE 3<span class="author" style="color:black">by AUTHOR3</span><span class="badge">Ongoing</span>
<em>Synopsis 3</em>
</a>
</li>
<li>
<a class="is-external-link" href="www.facebook.com">TITLE 2<span class="author" style="color:black">by AUTHOR3</span><span class="badge">Completed</span>
<em>Synopsis 2</em>
</a>
</li>
</ul>
Javascript:
function sortByCompleted(){
ul = document.getElementById("id01");
const li = ul.getElementsByTagName('li');
const sortedItems = Array.from(li).sort((a, b) => {
a = a.getElementsByClassName('badge')[0];
b = b.getElementsByClassName('badge')[0];
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
ul.append(sortedItems[0]);
}
If someone could give me a helping hand I'd be very grateful!