<html>
<head>
</head>
<body>
<span class="cena-vebsajt" id="amtTotal">$10.05</span>
+
<span class="cena-hosting" id="DeepGreenTotal">$5.08</span>
=
<span class="FinalTotal">$0.00</span>
<div>
<button type="button" id="btnCalculate">Calculate</button>
</div>
<script>
// Get element by ID
const getElById = (id) => document.getElementById(id);
// Get values from span
const getValuesFromSpan = (id) => parseFloat(getElById(id).textContent.replace('$', ''));
// Wait for the document to load
document.addEventListener('DOMContentLoaded', function() {
// Get the Calculate button element
var btnCalculate = getElById('btnCalculate');
// Attach click event handler to the Calculate button
btnCalculate.addEventListener('click', function() {
// Get the values from the spans
var amtTotal = getValuesFromSpan('amtTotal');
var DeepGreenTotal = getValuesFromSpan('DeepGreenTotal');
// Calculate the sum
var sum = amtTotal + DeepGreenTotal;
// Display the sum in the FinalTotal span
document.querySelector('.FinalTotal').textContent = '$' + sum.toFixed(2);
});
});
</script>
</body>
</html>
In the vanilla JavaScript code, we use the DOMContentLoaded event to ensure that JavaScript code executes after document is loaded.
One more thing by placing the JavaScript at the end of the HTML, it provides time to load HTML first and then load the javascript; this approach improves render speed.
We get the Calculate button element using getElementById and attach a click event listener to it using addEventListener.
When the button is clicked, we retrieve the values from the spans by getting the textContent and removing the dollar sign using the replace() method.
We parse the extracted values as floats using parseFloat().
Then, we calculate the sum of the two values and store it in the sum variable. Finally, we update the textContent of the. FinalTotal span with the calculated sum, formatted as a currency value using toFixed(2).