0

I need to sort (ascending/descending) some nested lists with TinySort.js and I need to be able to unsort them later (no jquery: just vanilla javascript, please).

As suggested by TinySort's author sjeiti, I used javascript to assign a position attribute to each list element before sorting them, so I can later recover their original order (unsort).

For a simple list, I had no problem (sort/unsort works well): https://jsfiddle.net/abubelinha/t7dcjhak/

For nested lists, I sorted them following this approach by Bergi. But I am not being able to unsort them later on. Here is what I achieved so far: https://jsfiddle.net/abubelinha/wn9o3gft/ ... but I am getting this error:
tinysort.min.js:10 Uncaught TypeError: d.getAttribute is not a function

var listElements = document.querySelectorAll('*');
function setInitialOrder() {
  for (var i = 0, l = listElements.length; i < l; i++) {
    listElements[i].setAttribute('position1', i);
  }
}
setInitialOrder();

function sortNested(sortby={}) {
  var lists = document.querySelectorAll('ul.memberlist');
  lists.forEach((li_item) => {
    tinysort(li_item.children, sortby);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinysort/3.2.5/tinysort.min.js"></script>
<ul class="memberlist">
   <li><a class="function">FFF</a></li>
   <li><a class="class">XXX</a>
      <ul class="memberlist">
      <li><a class="function">1x</a></li>
      <li><a class="function">3x</a></li>
      <li><a class="variable">2x</a></li>
      </ul>
   </li>
   <li><a class="class">AAA</a>
      <ul class="memberlist">
      <li><a class="variable">9a</a></li>
      <li><a class="function">5a</a></li>
      </ul>
   </li>
</ul>
<style> .tsort {background-color: lightgrey; padding: 3px; cursor:pointer; border:1px solid;} </style>
<span id="sortAZ" class="tsort" onclick="sortNested();">A-Z</span> 
<span id="sortZA" class="tsort" onclick="sortNested({order:'desc'});">Z-A</span> 
<span id="unsort" class="tsort" onclick="sortNested({attr:'position1'});">original order</span>

Thanks a lot in advance for your suggestions.

EDIT: code modified after @Thomas comment.
Changed from tinysort(li_item.childNodes, sortby);
to tinysort(li_item.children, sortby);

More info here.

abu
  • 422
  • 7
  • 14
  • 1
    `tinysort(li.children, sortby);` btw `li` is a poor choice of name for this variable as it contains an `
      `
    – Thomas Feb 22 '22 at 14:24
  • Thanks @Thomas , `.children` was the trick (I edited the code and now it works). But I don't understand why `.childNodes` worked for the A-Z and Z-A sortings, and not for the unsorting. If you could elaborate an answer explaining that, I would indeed accept it. As for your comment about inner `ul`, I don't get what you mean. – abu Feb 22 '22 at 18:55

0 Answers0