0

I have a html page with 3paragraphs and a button. In my JavaScript file, I created a function that adds 3 new paragraphs to the page each time I hit the button. These 3 new paragraphs should be copies of the existing ones, but each time be added in a randomised order. Here is my function

const body = document.querySelector("#body");
const paragraphs = document.querySelector(".paragraph");
const btnHitMe = document.querySelector("#btn");

const addParagraphs = () => {
  
  Array.prototype.forEach.call(paragraphs, (el) => {
    
    const node = document.createElement("P");
    node.innerHTML = el.innerHTML;

    body.insertBefore(node, btnHitMe);

  });

}

The above code adds the paragraphs successfully. My problem is how do I add these paragraphs in randomised order each time I hit the button?

Chinonso
  • 188
  • 3
  • 10

1 Answers1

0

First of all, querySelector does return only the 1st selected element.

Use querySelectorAll instead.


Secondly, Choose one of shuffle algorithms mentioned in another post, then use it to shuffle paragraphs before looping over it.


const paragraphs = document.querySelectorAll(".paragraph"); // <- here
// .... 
  // shuffle function should be added from: https://stackoverflow.com/a/2450976/747579
  let randomizedParagraphs = shuffle(Array.prototype.slice.call(paragraphs)) // <-- here
  Array.prototype.forEach.call(randomizedParagraphs, (el) => { // <- here
//....
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254