Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda