vendredi 23 août 2019

Radomize order of elements but group them by classes

I'm looking for a way to randomize the order of a list of <li> with jQuery but keeping them grouped by their class. So if I have like 3 levels of <li> I want them to appear in random order inside my <ul> but also keep the <li> with the highest level (defined by its class) grouped together at the top, then having the second highest group also in random order next, etc.

I have managed to use a function to reorder the items randomly but am not capable to group them by level. My knowledge of jQuery is quite basic.

Sample code before randomized order

<ul id="myList">
    <li class="level3"><a href="">Link #1</a></li>
    <li class="level3"><a href="">Link #2</a></li>
    <li class="level3"><a href="">Link #3</a></li>

    <li class="level2"><a href="">Link #4</a></li>
    <li class="level2"><a href="">Link #5</a></li>
    <li class="level2"><a href="">Link #6</a></li>
    <li class="level2"><a href="">Link #7</a></li>

    <li class="level1"><a href="">Link #8</a></li>
    <li class="level1"><a href="">Link #9</a></li>
    <li class="level1"><a href="">Link #10</a></li>
    <li class="level1"><a href="">Link #11</a></li>
    <li class="level1"><a href="">Link #12</a></li>
</ul>

and I'm looking to have something like this order randomly generated.

<ul id="myList">
    <li class="level3"><a href="">Link #3</a></li>
    <li class="level3"><a href="">Link #1</a></li>
    <li class="level3"><a href="">Link #2</a></li>

    <li class="level2"><a href="">Link #6</a></li>
    <li class="level2"><a href="">Link #4</a></li>
    <li class="level2"><a href="">Link #7</a></li>
    <li class="level2"><a href="">Link #5</a></li>

    <li class="level1"><a href="">Link #10</a></li>
    <li class="level1"><a href="">Link #12</a></li>
    <li class="level1"><a href="">Link #9</a></li>
    <li class="level1"><a href="">Link #8</a></li>
    <li class="level1"><a href="">Link #11</a></li>
</ul>




Aucun commentaire:

Enregistrer un commentaire