Skip to main content

Example : Round prices

Logic

Script to round prices

JS Code:

<script>

/* get all products to loop on */
function getProductElements(element) {
return [...element.querySelectorAll(`.fs-results-product-card`)];
}

function hooks() {
SerpOptions.registerHook('serp-product-grid', ({products, element}) => {
for (const productElement of getProductElements(element)) {
/* get product data */
if(productElement.dataset && productElement.dataset.productId && products[productElement.dataset.productId]){
const productID = productElement.dataset.productId;
const data = products[productID];
const priceEl = productElement.querySelector('.price-container .price');
if(priceEl && priceEl.textContent.match(/([.,0-9])+/gi,'') && priceEl.textContent.match(/([.,0-9])+/gi,'')[0] ){
let price = Number(priceEl.textContent.match(/([.,0-9])+/gi,'')[0]);
let roundedPrice = Math.round(price).toFixed(2);

if( !priceEl.classList.contains('isp-cstm-price') ){
priceEl.textContent = priceEl.textContent.replace(/([.,0-9])+/gi, roundedPrice);
priceEl.classList.add('isp-cstm-price');
}
}


}
}
});
}

// execution here
if (window.SerpOptions) {
hooks();
} else {
window.addEventListener('fast-serp-ready', function () {
hooks();
});
}
</script>