Home > front end >  Shuffle a container's DOM elements but not all in javascript
Shuffle a container's DOM elements but not all in javascript

Time:03-26

Trying to shuffle a container's (a div) DOM elements (other divs) with a particular class name ("div"). Other divs ("extra") should stay put in the place where they are.

So far I have used the modified shuffle algorithm from link

The code I have almost did the trick but the "Extra" div is appended at the bottom of the stack while it's supposed to stay atop.

let divs       = document.getElementsByClassName("div")
let divsNumber = divs.length;
let divver     = document.getElementsByClassName("divver")[0]

function shuffler() {
  for (var i = divsNumber; i >= 0; i--) {
    if (!divver.children[i].classList.contains("div")) {
      divver.appendChild(divver.children[Math.random() * i | 0]);
    }
  }
}
<div >
  <div >  Extra  </div>
  <div >    1  </div>
  <div >    2  </div>
  <div >    3  </div>
  <div >    4  </div>
  <div >    5  </div>
</div>

<button onclick="shuffler()" id="shuffles">Shuffle 'em</button>

Any hints greatly appreciated.

CodePudding user response:

const
  divver      = document.querySelector('div.divver')
, ShuffleDivs = divver.querySelectorAll('div.div') // just select this group
  ;
document.querySelector('button#shuffles').onclick = () =>
  {
  for (let i = ShuffleDivs.length; i >= 0; i--)
    {
    divver.appendChild(ShuffleDivs[Math.random() * i | 0])
    }
  }
<div >
  <div >  Extra  </div>
  <div >    1  </div>
  <div >    2  </div>
  <div >    3  </div>
  <div >    4  </div>
  <div >    5  </div>
</div>

<button id="shuffles">Shuffle 'em</button>

CodePudding user response:

Since you wish to leave the first element out of the shuffle and arrays of elements are 0 based you can change * i | 0] to * i | 1]

let divs       = document.getElementsByClassName("div")
let divsNumber = divs.length;
let divver     = document.getElementsByClassName("divver")[0]

function shuffler() {
  for (var i = divsNumber; i >= 0; i--) {
    if (!divver.children[i].classList.contains("div")) {
      divver.appendChild(divver.children[Math.random() * i | 1]);
    }
  }
}
<div >
  <div >  Extra  </div>
  <div >    1  </div>
  <div >    2  </div>
  <div >    3  </div>
  <div >    4  </div>
  <div >    5  </div>
</div>

<button onclick="shuffler()" id="shuffles">Shuffle 'em</button>

  • Related