innerText is undefined
I am trying to code a very basic shop for a school project and I tried to get the price of a product by using innerText in a function to update the total price in the cart but when I checked in the console I get this error:
caught TypeError: Cannot read properties of undefined (reading 'innerText')
The function code:
16 Replies
that likely maens
cartRow.getElementsByClassName("cart-price")[0]
is undefined, so it didn't find anythingbut I do get an output to the console when I do
console.log(priceElement);
I get this:
<td class="cart-price">$699</td>
it's probably best to make a codepen then, without the code running or at least being able to see the HTML, I don't have any other ideas
Ok
unless you retyped the code up there and there's a typo somewhere
I just need to warn you that the design is terrible
I'm mostly a backend developer, I won't judge
I like the backend more but I'm still at the very start so I don't know what comes next in this area
https://codepen.io/SuperTesmon/pen/ZEqgZxK
You're getting
TypeError: priceElement is undefined
because cartRows
includes the cart header, which also has the class cart-row
on there
when you have the console.log uncommented, you get three results, one undefined, and two rows (which are the two items in the cart already)
when you have the let price
line uncommented, you're getting one error because the header row doesn't have a cart-price
element
the error then stops execution of the click handler. If you use the optional chaining syntax:
you get undefined, $699, $699 instead
the solution is to skip the first row somehow, either by removing the cart-price
class, or starting your for loop at 1 instead of 0 so you skip the first result
You may want to take a look at querySelector
/ querySelectorAll
over getElementBy*
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAllI removed the
cart-price
class because it's much easier and I think starting from 1 in the loop could make it riskier later when I add more codecool
Thank you very much
no problem, glad to help 🙂
Is there any way to close the thread with commands or something or I just need to mark it as solved?
just mark it as solved, it'll get archived eventually
I see you already added the tag, so you're all set 🙂
Yes, thank you again