How can I check an element if it is exists in the parent element? I'm implementing an increase/decrease button for product quantity in my project. I can increase and decrease the quantity when the user clicks those buttons. I have a _parentElement which I render an element and data and the error message (this will only render when there's an error). I've attached a click event to that _parentElement (this is visible in the DOM) and do event delegation.
This error will only log when the error message is rendered in the _parentElement and when I click on the _parentElement.
Error: Cannot read properties of null (reading 'innerHTML') at DetailView._handlerQuantity
This what I did:
View.js
import icons from 'url:../../icons/icons.svg';
export default class View {
_data;
renderError(message = this._errorMessage) {
const html = /*html*/ `
<div class="flex flex-col items-center justify-center gap-4 min-h-[inherit]">
<svg class="h-6 w-6 sm:h-10 sm:w-10 fill-red-600">
<use xlink:href="${icons}#icon-warning"></use>
</svg>
<span class="text-xl text-neutral-600 font-medium sm:text-xl xs:text-lg">${message}</span>
</div>
`;
const markup = this._parseStringtoHTML(html);
this._parentElement.innerHTML = '';
this._parentElement.insertAdjacentElement('afterbegin', markup.body.firstElementChild);
}
}
DetailView.js
class DetailView extends View {
_parentElement = document.querySelector(".product__details");
_errorMessage = "We could'nt find the product. Please try another one!";
constructor() {
super();
this._addHandlerProductQuanity();
}
_handlerQuantity(e) {
const increase = e.target.closest(".btn__control--add");
const decrease = e.target.closest(".btn__control--minus");
let quantity = document.querySelector(".product__quantity");
const currentValue = Number(quantity.innerHTML) || 0;
if (increase)
Number(quantity.innerHTML) < this._data.stocks
? (quantity.innerHTML = currentValue + 1)
: 1;
if (decrease)
Number(quantity.innerHTML > 1)
? (quantity.innerHTML = currentValue - 1)
: 1;
}
_addHandlerProductQuanity() {
this._parentElement.addEventListener(
"click",
this._handlerQuantity.bind(this)
);
}
}
HTML:
<main class="main min-h-[calc(100vh-5rem)] sm:min-h-[calc(100vh-8rem)]">
<section class="product__details min-h-[inherit]">
<!-- PRODUCTS DETAILS WILL GO HERE... -->
</section>
</main>