Cannot Read property addEventListener of undefined?

var removeButton = document.getElementsByClassName('remove-btn')
  console.log(removeButton)
for(var i = 0; i <= removeButton.length; i++){
  var button = removeButton[i]
  button.addEventListener('click',function(event) {
    console.log('clicked')
      var buttonClicked = event.target
    buttonClicked.parentElement.parentElement.remove()
  })
}

hello there,
I am very much new to javascript and the code that I have listed above should remove an item from the cart but my code does not enter the addEventListener method throwing back an error that says

Cannot Read property addEventListener of undeifined

can anybody help?

What does your HTML look like?

<div class="order-col">
								<div><strong>Product Total</strong></div>
							</div>
							<div class="order-products">
								<div class="order-col">
									<div>item1</div>
										<img src="products/fig.jpg" alt=""><br>
										<button type="button" name="button" class="remove-btn">Remove</button>
									<div>$980.00</div>

this is my html

Js isn’t my strongpoint but shouldn’t you be looking for less than and not less than or equal to in your loop. Your loop starts at zero.

e.g.

for(var i = 0; i < removeButton.length; i++)

2 Likes

so basic , no idea how is missed it ,
Thank you

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.