Search code examples
javascriptcalculator

i have made a calculator using html ,css and javascript and its not working


[HTML code

it is a simple calculator html code that's why I haven't posted it full

](https://i.sstatic.net/ET5Cu.png) [JavaScript code : the main issue is with the JavaScript code which needs to be focused on .

](https://i.sstatic.net/im0ND.png)


Solution

  • since the script is placed in head section and the HTML content is not yet rendered it is not able to get the elements using query selectors. Try placing the script at the end of body

    HTML Script

    let input = document.getElementById("display");
    let buttons = document.querySelectorAll("button");
    
    let string = "";
    buttons.forEach((button) => {
      button.addEventListener("click", (event) => {
        string += event.target.innerHTML;
        console.log(string);
      });
    });
    <html>
    
    <head>
    </head>
    
    <body>
        <div>
            <div>
                <input id="display" type="text" />
            </div>
            <button> 1 </button>
            <button> 2 </button>
        </div>
        <script src="script.js"></script>
    </body>
    
    </html>