Tom Yotwongjai
Tom Yotwongjai

Reputation: 67

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

Upvotes: 0

Views: 81

Answers (2)

Never Serious
Never Serious

Reputation: 91

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

Upvotes: 1

0stone0
0stone0

Reputation: 43983

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

Upvotes: 0

Related Questions