Convert Temperatures from Celsius to Fahrenheit in a HTML table
Use this Javascript code to convert the temperatures in a HTML table from Celsius to Fahrenheit.
Make sure you add a button to your page, somewhere above the table with the id "convert-button".
I am also changing the text of a span element with the id "table-footer" to reflect the new values.
Also, using the Math.round function, when the conversion is performed, the new values are rounded in order to avoid decimals.
const button = document.getElementById('convert-button'); button.addEventListener('click', function() { const footer = document.getElementById('system'); // Get all the cells in the table const cells = document.querySelectorAll('td'); cells.forEach(function(cell) { // Check if the cell's text content includes the degree symbol if (cell.textContent.charCodeAt(cell.textContent.length - 1) === 176) { // Get the temperature value and convert it to a number let celsius = parseInt(cell.textContent.replace('°', '')); // Convert the temperature from Celsius to Fahrenheit let fahrenheit = Math.round((celsius * 9 / 5) + 32); // Update the cell with the new temperature value cell.innerHTML = fahrenheit + '°'; } }); footer.textContent = 'Fahrenheit (imperial system)'; });
Comments
Post a Comment