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

148
Views
¿Cómo puedo hacer esto mejor y más limpio?

Tengo este código que elimina elementos en la clase btn-danger. Solo quiero saber qué puedo usar en lugar de for loop para hacer que el código sea más limpio:

 var removeCartItemButtons = document.getElementsByClassName('btn-danger'); for (var i = 0; i < removeCartItemButtons.length; i++) { var button = removeCartItemButtons[i]; button.addEventListener('click', function (e) { var buttonClicked = e.target; buttonClicked.parentElement.parentElement.remove(); }); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Mejora general

  • Utilice let en lugar de var . Mira esto
  • Si solo está accediendo a una variable y no la está cambiando, use const en lugar de let .
  • document.querySelectorAll() o document.querySelector() son en algunos casos (como en su caso) mejores que getElementsByClassName o getElementById o getElementsByTagName .
  • Al iterar sobre matrices o listas de nodos estáticos, forEach es generalmente una opción mejor (más legible) que un bucle for . ( querySelectorAll devuelve una lista de nodos estáticos. No necesita Array.from , pero si desea usar otros métodos específicos de Array, use Array.from como señaló @Yousaf)
  • Utilice la function en el ámbito global y para las propiedades de Object.prototype . Utilice class para constructores de objetos. Use => en cualquier otro lugar. Mira esto.

Así es como lo habría escrito

 document.querySelectorAll('.btn-danger').forEach(btn=>btn.addEventListener('click',e=>e.target.parentElement.parentElement.remove()))
about 4 years ago · Juan Pablo Isaza Report

0

Su código se puede acortar a:

 Array.from(document.getElementsByClassName('btn-danger')).forEach((button) => { button.addEventListener('click', (e) => { e.target.parentElement.parentElement.remove(); }); });

Esto usa:

  • Array.from().forEach() :
    • Cómo iterar correctamente a través de getElementsByClassName >
  • Funciones de flecha
    • ¿Cuál es el significado de "=>" (una flecha formada por igual y mayor que) en JavaScript?

Dado que las funciones de matriz se pueden reescribir sin {} , una sola línea se vería así:

 Array.from(document.getElementsByClassName('btn-danger')).forEach((button) => button.addEventListener('click', (e) => e.target.parentElement.parentElement.remove()));
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!