Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda