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

91
Views
Reorganizar orger de niños en Javascript no funciona varias veces

Tengo el siguiente código para mover el orden de los niños en un elemento. Cuando hago clic una vez, funciona bien, pero cuando hago clic varias veces, solo funciona cada 2 o 3 veces.

 const prevP = () => { const pList = document.getElementById("project-list") const firstProject = pList.firstChild; const lastProject = pList.lastChild; pList.insertBefore(lastProject, firstProject); } const nextP = () => { console.log("next"); const pList = document.getElementById("project-list") const firstProject = pList.firstChild; let lastProject = pList.lastChild; pList.insertBefore(firstProject, lastProject); }
 <span class="material-icons md-48 close icon-btn" onclick="prevP()" >navigate_before</span > <div class="project-list" id="project-list"> <div class="project"> <img href="protfolio" alt="" /> <p>My Portfolio 1</p> </div> <div class="project"> <img href="protfolio" alt="" /> <p>My Portfolio 2</p> </div> <div class="project"> <img href="protfolio" alt="" /> <p>My Portfolio 3</p> </div> <div class="project"> <img href="protfolio" alt="" /> <p>My Portfolio 4</p> </div> <div class="project"> <img href="protfolio" alt="" /> <p>My Portfolio 5</p> </div> </div> <span class="material-icons md-48 close icon-btn" onclick="nextP()" >navigate_next</span >

También me di cuenta de que a veces el código altera el orden de los elementos al usar ambos botones, y no tengo idea de por qué sucede esto.

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

0

La causa de ese comportamiento es que usa firstChild y lastChild . Estos pueden seleccionar nodos de texto con solo algunos espacios en blanco. Cámbielos a firstElementChild y lastElementChild .

En segundo lugar, la acción "Siguiente" no debe insertar el primer elemento antes del último elemento, sino después . Para eso puedes usar el método appendChild :

 pList.appendChild(firstProject);
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!