TinySort icon indicating copy to clipboard operation
TinySort copied to clipboard

sort nested elements ... and unsort

Open abubelinha opened this issue 2 years ago • 0 comments

I think this is a mix of #125 (unsorting, which I successfully implemented, but in a simple non-nested way) and #107 (nested divs, but much simpler than my example).

In my case this is what I am trying to do:

initial order

  • ZZZ
  • XXX
    • FFF
    • BBB
  • AAA
    • ZZZ
    • EEE

AZ order

  • AAA
    • EEE
    • ZZZ
  • XXX
    • BBB
    • FFF
  • ZZZ

This is the nested code:

<ul class="memberlist">
   <li>
     <a class="function">ZZZ</a>
   </li>
   <li>
     <a class="class">XXX</a>
      <ul class="memberlist">
      <li>
        <a class="function">CCC</a>
      </li>
      <li>
        <a class="variable">BBB</a>
      </li>
      </ul>
   </li>
   <li>
     <a class="class">AAA</a>
      <ul class="memberlist">
      <li>
        <a class="variable">ZZZ</a>
      </li>
      <li>
        <a class="function">EEE</a>
      </li>
      </ul>
   </li>
</ul>

As you can see, the sortable strings are text inside <a> tags which can belong to different css classes (although I don't know if this is relevant to the sorting/unsorting problem). So I have two questions:

  1. I can't figure out the way to sort this while keeping the inner structure of each list item (the <a> element must be kept before the inner <ul> -if there is any-, and the <ul> list items must be sorted the same way). This is what I tried: tinysort('ul.memberlist>li>ul>li');
  2. Although I understood #125 , I don't know which elements of my html code should receive a numeric value property which lets me unsort nested list to recover the original order. This is what I tried, following the example in #125 (but as I said in 1, I am not being able to sort/unsort outer list)
<script type="text/javascript">
var listElements = document.querySelectorAll('li');
for (var i = 0, l = listElements.length; i < l; i++) {
	listElements[i].setAttribute('value', i);
}
tinysort('ul.memberlist>li>ul>li'); // TO SORT
tinysort('ul.memberlist>li',{attr:'value'}); // TO UNSORT
</script>

I put an example here: https://jsfiddle.net/abubelinha/795xwdLf/ . But it only sorts the innermost lists, and it does it bad (items are sorted as a whole list, instead of being kept inside their parents -nested sorting-).

  1. An additional problem is that I don't know in advance if there will be any inner nested lists or not (sometimes, the page only has the outer list)

Thanks a lot in advance for any help you can provide EDIT: also posted question in Stackoverflow

abubelinha avatar Feb 20 '22 18:02 abubelinha