I am trying to develop a theme on Shopify. I have used JavaScript to generate the HTML. Can you please confirm if this approach is correct? I have attached my code (Cart Drawer). Please confirm if I can code it this way.
function fetchCart() {
fetch(‘/cart.js’)
.then(response => response.json())
.then(cart => {
console.log(‘Cart data:’, cart);
const cartItemsList = document.getElementById(‘cart-items-list1’);
const totalElement = document.getElementById(‘cart-total1’);
if (cartItemsList && totalElement) {
$(‘.collections_info’).show();
cartItemsList.innerHTML = ‘’;
let total = 0;
if (cart.items.length === 0) {
document.getElementById(‘cart_totalinfo’).style.display=“none”;
document.getElementById(‘collections_info’).style.display=“block”;
} else {
$(‘.collections_info’).hide();
cart.items.forEach(item => {
total += item.line_price;
cartItemsList.innerHTML += `
totalElement.textContent = Sub total: Rs. ${(total / 100).toFixed(2)};
} else {
console.error(‘Cart items list or total element not found.’);
}
})
.catch(error => console.error(‘Error fetching cart:’, error));
}