Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How to re-order elements in a forEach call JavaScript

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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
//....
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!