Home > Software design >  Variable not getting defined
Variable not getting defined

Time:12-03

One of my event’s variables isn’t getting defined.

The title variable isn’t getting defined so I think I made a mistake.

var addToCartButtons = document.getElementsByClassName('item-button')

for (var i = 0; i < addToCartButtons.length; i  ) {
  var button = addToCartButtons[i]
  
  button.addEventListener('click', addToCartClicked)
}

function addToCartClicked(event) {
  var button = event.target
  var shopItem = button.parentElement.parentElement
  var title = storeitem.getElementsByClassName('product-name')[0].innerHTML
  
  console.log('title')
}
<div >
  <span >CPU 1</span>
  <img  src="Images/CPU-1.jpg">
  <div >
    <span >$229.99</span>
    <button  role="button">ADD TO CART</button>
  </div>
</div>

CodePudding user response:

It looks like there is a typo in the addToCartClicked function. The title variable is defined as storeitem.getElementsByClassName('product-name')[0].innerHTML, but it should be shopItem instead of storeitem. The shopItem variable is defined earlier in the function as button.parentElement.parentElement, so changing storeitem to shopItem should fix the issue.

Additionally, the console.log statement currently prints the string 'title' instead of the value of the title variable.

CodePudding user response:

Fix your code. you need that shopItem as discribe above by Mr.Sebastian Simon and Mr.haggbart.

var addToCartButtons = document.getElementsByClassName('item-button')

for (var i = 0; i < addToCartButtons.length; i  ) {
  var button = addToCartButtons[i]
  button.addEventListener('click', addToCartClicked)
}

function addToCartClicked(event) {
  var button = event.target
 
  var shopItem = button.parentElement.parentElement

  // error here 'storeitem' variable is defined.
  var title = shopItem.getElementsByClassName('product-name')[0].innerHTML
  
  console.log('title')
  console.log(title)  // you means title varible
}
<div >
  <span >CPU 1</span>
  <img  src="Images/CPU-1.jpg">
  <div >
    <span >$229.99</span>
    <button  role="button">ADD TO CART</button>
  </div>
</div>

CodePudding user response:

function addToCartClicked(event) {
  var button = event.target
  var shopItem  = button.parentElement.parentElement
  var title = shopItem.getElementsByClassName('product-name')[0].innerHTML
  console.log(title)
}
  • Related