Reputation: 5
I created a dynamic template to populate products with pricing pulled directly from the catalog. However, when a particular product is not on sale, there is still strikethrough pricing with the regular price even though they are both the same. I initially created two variables, if they equal each other, to set the regularPrice = null. However that is not working. I am new to javascript and help would be appreciated!
strikethrough pricing:
my code:
const regularPrice = document.querySelector("span.pr__price--inactive").textContent;
const salePrice = document.querySelector("span.pr__price--active").textContent;
if (regularPrice === salePrice){
regularPrice === null;
}
markup:
{{#if attributes.price.value}}
<p class="pr__price">
<span class="pr__price--active">
<span data-locale="en_US" data-currencycode="USD">$</span>
{{attributes.price.value}}
</span>
{{#if attributes.listPrice.value}}
<span class="pr__price--inactive">
<span data-locale="en_US" data-currencycode="USD">$</span>
{{attributes.listPrice.value}}
</span>
{{/if}}
</p>
Upvotes: 0
Views: 122
Reputation: 11613
Extracting values from your UI for comparison-- particularly if you have access to the raw data you're pulling-- is less than ideal. So I'll start by saying this is probably not a great approach.
However, I'll attempt to answer your question since you're missing a few important points.
regularPrice
. Don't make it a const
if it might change!===
is for strict equality comparison, not assignment. You're trying to use it for assignment.span.pr__price--inactive
and span.pr__price--active
? Using IDs here would allow you to be specific.textContent
will return text. That's what you're attempting to compare. Shall we convert that to numeric value?let regularPriceElement = document.querySelector("span.pr__price--inactive"); //this is a handle to the HTML element
let regularPrice = regularPriceElement.textContent; //this is a snapshot of the value in that element
let salePrice = document.querySelector("span.pr__price--active").textContent;
regularPrice = +regularPrice; //convert to a number
salePrice = +salePrice; //convert to a number
console.log(regularPrice, salePrice, regularPrice === salePrice);
if (regularPrice === salePrice){
regularPriceElement.textContent = "(blank)"; //blank out the element content
//or add strike-through
regularPriceElement.style.textDecoration = "line-through";
}
<div>
<span class="pr__price--active">1.99</span>
</div>
<div>
<span class="pr__price--inactive">1.99</span>
</div>
Upvotes: 1
Reputation: 45
It is worth checking which will be getting to the code before checking if they are equal. log them using console.log() or use a debugger. Also using the query selector the first element of your class will be returned but you need to parse it using parseInt or parseDouble beforehand to make the comparison.
Upvotes: 0