简体   繁体   中英

How to shuffle inner div contents using Javascript?

I want to shuffle the inner contents of a div using javascript. I can shuffle the div positions but cannot shuffle the inner contents. I want to shuffle in such a way that will return like Position 1: Third, Position 2: First, Position 3: Second and so on. I can shuffle the div positions like below but cannot update the contents. Can anyone help?

 shuffle(); function shuffle() { var container = document.getElementById("mainshuffle"); var elementsArray = Array.prototype.slice.call(container.getElementsByClassName("diffpos")); elementsArray.forEach(function (element) { container.removeChild(element); }); shuffleArray(elementsArray); elementsArray.forEach(function (element) { container.appendChild(element); }); } function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }
 <div id="mainshuffle"> <div class="diffpos"> <p>Position 1: First</p> <img src="position1.jpg"> </div> <div class="diffpos"> <p>Position 2: Second</p> <img src="position2.jpg"> </div> <div class="diffpos"> <p>Position 3: Third</p> <img src="position3.jpg"> </div> </div>

If you just want to change the content of p tag refactor your html like this

<div id="mainshuffle">
  <p id="p_shuffle">Position 1: First</p>
  <img class="img_shuffle" src="...">
</div>

Store the content in a array for example:

const contentArr = ['position 1: first', 'position 2: second', 'position 3: third']

then change the content of p tag by using contentArr index like this

function shuffleContent(i) {
  // i is the index of content you want to use depending on which content you want
  const newContent = contentArr[i];
  const shuffleP = document.getElementById('p_shuffle');
  shuffleP.textContent = newContent;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM