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

143
Views
How do I make this better and cleaner?

I have this code that remove Items in class btn-danger. I just want to know what can I use instead of for loop to make the code cleaner:

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

General Improvement

  • Use let instead of var. See This
  • If you're just accessing a variable and not changing it, use const instead of let.
  • document.querySelectorAll() or document.querySelector() are in some cases (like in your case) better than getElementsByClassName or getElementById or getElementsByTagName.
  • When iterating over arrays or static node lists, forEach is generally a better (more readable) option than a for loop. (querySelectorAll returns a static node list. You don't need Array.from, but if you want to use other Array specific methods use Array.from as @Yousaf pointed out)
  • Use functionin the global scope and for Object.prototype properties. Use class for object constructors. Use => everywhere else. See This.

Here is how I would have written it

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

0

Your code can be shortened to:

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

This uses:

  • Array.from().forEach():
    • How to correctly iterate through getElementsByClassName>
  • Arrow functions
    • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Since the array functions can be re-written without the {}, an one-liner would look like:

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!