Home > front end >  innerText of HTML is undefined, but shouldn't be
innerText of HTML is undefined, but shouldn't be

Time:12-22

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 >Breakfast Club Blue Hoodie</h4>
<div >
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
</div>
<p>$55.00<i ></i></p>
</div>

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

CodePudding user response:

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 realParent = shopProducts.parentElement
var title = realParent.getElementsByClassName("product-title")[0].innerText;
console.log(title);
}

or you could just do it like:

var shopProducts = button.parentElement.parentElement

CodePudding user response:

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

  • Related