简体   繁体   中英

Toggle between icons depending on number of child elements

I figured out how to change the icon when more elements are added, but I can't figure out to how return it to the original icon while the cart is empty.

Javascript

let cartItems = document.getElementsByClassName('cart-container')[0];

if (cartItems.childElementCount <= 1) {
    let cartBtn = document.getElementsByClassName('cart-btn')[0]
    cartBtn.innerHTML = `
    <i class="fa fa-cart-plus cart-btn text-danger"></i>`
}

HTML

<h1 class="cart-btn">
  <i class="fa fa-shopping-cart"></i>
</h1>

<div class="container cart-container d-flex flex-column pb-5">
  <div class="row mt-5 mb-4">
    <div class="col">
    </div>
  </div>
</div>

I have a shopping cart button on a navbar that I need to switch between different states depending on if the cart is empty or not. I figured out how to change it to one state when an item was added to the cart, but couldn't figure out how to change it back to the original state when I emptied the cart. However, I used this code to accomplish that task.

Javascript

function checkNavBtn() {
    let cartItems = document.getElementsByClassName('cart-container')[0];
    let cartBtn = document.getElementsByClassName('fa-shopping-cart')[0];
    if (cartItems.childElementCount >= 0) {
        cartBtn.classList.add('fa-cart-plus', 'text-danger');
    } if (cartItems.childElementCount <= 0) {
        cartBtn.classList.remove('fa-cart-plus', 'text-danger');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM