John Zhang
John Zhang

Reputation: 21

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

Upvotes: 1

Views: 241

Answers (2)

PhilCowan
PhilCowan

Reputation: 533

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

Upvotes: 2

Ra Zi
Ra Zi

Reputation: 17

function addCartClicked(event) {
  var button = event.target;
  var shopProducts = button.parentElement
  var title = button.parentNode.previousElementSibling.previousElementSibling.innerText;
  console.log(title);
}

This is not a good method but may help you get your result

Upvotes: 0

Related Questions