javascripttypeerrorundefinedinnertext

innerText of HTML is undefined, but shouldn't be


The error is:

Cannot read properties of undefined (reading 'innerText')

I get this error when I try to run my code.

var addCart = document.getElementsByClassName("add-cart");

for (var i = 0; i < addCart.length; i++) {
  var button = addCart[i];
  button.addEventListener("click", addCartClicked);
}


function addCartClicked(event) {
  var button = event.target;
  var shopProducts = button.parentElement
  var title = shopProducts.getElementsByClass("product-title")[0].innerText;
  console.log(title);
}
<h4 class="product-title">Breakfast Club Blue Hoodie</h4>
<div class="rating">
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
  <i class="fa fa-star"></i>
</div>
<p>$55.00<i class="fa fa-cart-plus add-cart"></i></p>
</div>

I expected whats in "product-title" to appear on the console


Solution

  • The parent element of the icon that you click is the p tag, so you need to go up one more level.

    var addCart = document.getElementsByClassName("add-cart");
    for (var i = 0; i < addCart.length; i++){
        var button = addCart[i];
        button.addEventListener("click", addCartClicked);
    }
    
    function addCartClicked(event){
    var button = event.target;
    var shopProducts = button.parentElement
    var grandParent = shopProducts.parentElement
    var title = grandParent.getElementsByClassName("product-title")[0].innerText;
    console.log(title);
    }
    

    or you could just do it like:

    var shopProducts = button.parentElement.parentElement