Home > Software design >  How to target the basket value only in a div with multiple values
How to target the basket value only in a div with multiple values

Time:11-09

I've got a piece of code where i want to target the basket total only and if the amount is more then €40 i want it to print a string to state this or if its under the amount then to print something else.

The issue i have is the div that wraps around the total basket amount states the number of items that are in your basket as well. I can't change the existing code on the cart so is there a way i can target the basket price in this div only?

var patternPrice = /[^0-9\.]/g;  
var targetBasketTotal = document.querySelector('.cart');
var totalAmount = parseFloat(targetBasketTotal.textContent.replace(patternPrice, "")) / 100;
console.log(totalAmount);

if(totalAmount < 40) {
  targetBasketTotal.insertAdjacentHTML("afterend", "<section class='message'>Basket is less then €40</section>");
} else {
  targetBasketTotal.insertAdjacentHTML("afterend", "<section class='message'>Basket is more then €40</section>");
}
<div class="cart">10 items | €&nbsp;38,87</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use split with your replace for select just price like:

var patternPrice = /[^0-9\.]/g;  
var targetBasketTotal = document.querySelector('.cart');
var totalAmount = parseFloat(targetBasketTotal.textContent.split('|')[1].replace(patternPrice, "")) / 100;
console.log(totalAmount);

if(totalAmount < 40) {
  targetBasketTotal.insertAdjacentHTML("afterend", "<section class='message'>Basket is less then €40</section>");
} else {
  targetBasketTotal.insertAdjacentHTML("afterend", "<section class='message'>Basket is more then €40</section>");
}
<div class="cart">10 items | €&nbsp;38,87</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Reference:

PS. Obviously the structure must be the same

  • Related