简体   繁体   中英

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();
 });
}

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:


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()));

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 function in 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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM