elena1234

QuerySelector - how to select in JavaScript

Oct 11th, 2021 (edited)
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.   let numberButtons = document.querySelectorAll('[data-number]');
  3.   let operationButtons = document.querySelectorAll('[data-operation]');
  4.   let equalsButton = document.querySelector('[data-equals]');
  5.   let clearButton = document.querySelector('.clear');
  6.  
  7.   let expressionOutput = document.getElementById('expressionOutput');
  8.   let resultOutput = document.getElementById('resultOutput');
  9.  
  10.   for (const button of numberButtons) {
  11.     button.addEventListener('click', () => {
  12.       expressionOutput.innerHTML += button.innerHTML;
  13.     })
  14.   }
  15.  
  16.   for (const button of operationButtons) {
  17.     button.addEventListener('click', () => {
  18.       expressionOutput.innerHTML += ` ${button.innerHTML} `;
  19.     }, { once: true });
  20.   }
  21.  
  22.   equalsButton.addEventListener('click', () => {
  23.     let currentExpressionOutput = expressionOutput.innerHTML.split(' ');
  24.     let result = '';
  25.     if (currentExpressionOutput[1] === '+') {
  26.       result = parseFloat(currentExpressionOutput[0]) + parseFloat(currentExpressionOutput[2]);
  27.     } else if (currentExpressionOutput[1] === '-') {
  28.       result = parseFloat(currentExpressionOutput[0]) - parseFloat(currentExpressionOutput[2]);
  29.     } else if (currentExpressionOutput[1] === 'x') {
  30.       result = parseFloat(currentExpressionOutput[0]) * parseFloat(currentExpressionOutput[2]);
  31.     } else {
  32.       result = parseFloat(currentExpressionOutput[0]) / parseFloat(currentExpressionOutput[2]);
  33.     }
  34.  
  35.     currentExpressionOutput.innerHTML = '';
  36.     resultOutput.innerHTML = result;
  37.   })
  38.  
  39.   clearButton.addEventListener('click', () => {
  40.     expressionOutput.innerHTML = '';
  41.     resultOutput.innerHTML = '';
  42.   })
  43. }
  44.  
  45.  
Add Comment
Please, Sign In to add comment