Advertisement
-Annie-

07.SumTable

Jun 26th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="UTF-8">
  5.         <title>Homework-DOM</title>
  6.     </head>
  7.  
  8.     <body>
  9.     <table>
  10.         <tbody>
  11.         <tr><th>Product</th><th>Cost</th></tr>
  12.         <tr><td>Beer</td>   <td>2.88</td></tr>
  13.         <tr><td>Fries</td>  <td>2.15</td></tr>
  14.         <tr><td>Burger</td> <td>4.59</td></tr>
  15.         <tr><td>Total:</td> <td id="sum"></td></tr>
  16.         </tbody>
  17.     </table>
  18.     <button onclick="sum()">Sum</button>
  19.  
  20.     <script>
  21.         function sum() {
  22.             let pricesCollection = document.querySelectorAll('td:last-child');
  23.             let result = [];
  24.             let total = document.getElementById('sum');
  25.  
  26.             for(let i = 0; i < pricesCollection.length; i++){
  27.                 let price = Number(pricesCollection[i].textContent);
  28.                 result.push(price);
  29.             }
  30.  
  31.             total.textContent = result.reduce((a,b) => a + b);
  32.         }
  33.     </script>
  34.  
  35.     </body>
  36. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement