Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this?

var input = document.getElementById('input');
var result = document.getElementById('result');
var button = Array.from(document.getElementsByClassName('btn'));
button.forEach(function (btn) {
    btn.addEventListener('click', function (e) {
        console.log('hfello');
    });
});
@import url('https://fonts.googleapis.com/css2?family=Epilogue:wght@400;800&display=swap');
*{
    margin: auto;
    padding: 0;
    font-family: 'Epilogue', sans-serif;
}
body{
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
}
body >div{
    max-width: 500px;
    margin: 50px auto;
    border-radius: 10px;
    background: linear-gradient(to bottom, #2e2e2e, #000000);
}
body >div div:first-child{
    width: 100%;
}
.input{
    color: white;
    font-size: 30px;
    padding: 10px;
    direction: rtl
}
.result{
    color: white;
    font-size: 30px;
    padding: 10px;
    direction: rtl
}

body div div:last-child{
    display: grid;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    justify-content: center;
    align-items: center;
    gap: 10px;
    padding: 10px
}
button{
    padding: 20px 30px;
    font-size: 30px;
    color: white;
    background: #2e2e2e;
    border: none;
    border-radius: 50%;
}
button:first-child{
    grid-column: 1/3;
}
button:nth-child(2){
    grid-column: 3/5;
}
.style1{
    background-color: gray;
}
.style2{
    background-color: rgb(204, 137, 12);
}

@media (max-width:900px){
    body > div{
        width: 100%;
        height: 100vh;
        margin: auto;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Calculator</title>
</head>
<body>
    <div>
        <div>
            <p class="input" id="input">0</p>
            <p class="result" id="result">result</p>
        </div>
        <div>
            <button class="style1" id="test" >AC</button>
            <button class="style1" id="btn">Dell</button>
            <button id="btn">7</button>
            <button id="btn">8</button>
            <button id="btn">9</button>
            <button class="style2">×</button>
            <button id="btn">4</button>
            <button id="btn">5</button>
            <button id="btn">6</button>
            <button class="style2">÷</button>
            <button id="btn">1</button>
            <button id="btn">2</button>
            <button id="btn">3</button>
            <button class="style2" id="btn">-</button>
            <button id="btn">0</button>
            <button id="btn">.</button>
            <button class="style2" id="btn">=</button>
            <button class="style2" id="btn">+</button>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>

Answer №1

When looking to select your buttons, avoid using the following method:

var button = Array.from(document.getElementsByClassName('btn'));

This is because the button elements do not have a "btn" class associated with them.

Instead, try changing the line to:

var button = Array.from(document.querySelectorAll('button'));

By doing so, all buttons will be selected based on their element type.

Check out this JsFiddle for reference.

Answer №2

var input = document.getElementById('input');
var result = document.getElementById('result');
var button = Array.from(document.getElementsByClassName('btn'));
button.forEach(function (btn) {
    btn.addEventListener('click', function (e) {
        console.log('hfello');
    });
});
@import url('https://fonts.googleapis.com/css2?family=Epilogue:wght@400;800&display=swap');
*{
    margin: auto;
    padding: 0;
    font-family: 'Epilogue', sans-serif;
}
body{
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
}
body >div{
    max-width: 500px;
    margin: 50px auto;
    border-radius: 10px;
    background: linear-gradient(to bottom, #2e2e2e, #000000);
}
body >div div:first-child{
    width: 100%;
}
.input{
    color: white;
    font-size: 30px;
    padding: 10px;
    direction: rtl
}
.result{
    color: white;
    font-size: 30px;
    padding: 10px;
    direction: rtl
}

body div div:last-child{
    display: grid;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    justify-content: center;
    align-items: center;
    gap: 10px;
    padding: 10px
}
button{
    padding: 20px 30px;
    font-size: 30px;
    color: white;
    background: #2e2e2e;
    border: none;
    border-radius: 50%;
}
button:first-child{
    grid-column: 1/3;
}
button:nth-child(2){
    grid-column: 3/5;
}
.style1{
    background-color: gray;
}
.style2{
    background-color: rgb(204, 137, 12);
}

@media (max-width:900px){
    body > div{
        width: 100%;
        height: 100vh;
        margin: auto;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Calculator</title>
</head>
<body>
    <div>
        <div>
            <p class="input" id="input">0</p>
            <p class="result" id="result">result</p>
        </div>
        <div>
            <button class="style1 btn" id="ac" >AC</button>
            <button class="style1 btn" id="dell">Dell</button>
            <button class="btn">7</button>
            <button class="btn">8</button>
            <button class="btn">9</button>
            <button class="style2 btn">×</button>
            <button class="btn">4</button>
            <button class="btn">5</button>
            <button class="btn">6</button>
            <button class="style2 btn">÷</button>
            <button class="btn">1</button>
            <button class="btn">2</button>
            <button class="btn">3</button>
            <button class="style2 btn" id="btn">-</button>
            <button class="btn">0</button>
            <button class="btn">.</button>
            <button class="style2 btn" id="btn">=</button>
            <button class="style2 btn" id="btn">+</button>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>

  • change id="btn" to class="btn"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for temporarily preventing a digest cycle when modifying a scope variable

Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...

What is the process to retrieve a function from a router javascript file using node.js?

Dealing with a web application that is not my own, I now have the task of sending out one hundred emails. Unfortunately, the code is poorly documented and written, which means I need to test it to figure out what I can and cannot do. However, I'm uns ...

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

Ensure the detection of 404 error status using jQuery

My current approach involves using this code snippet to retrieve data from Twitter through its API: $.ajax({ url : apiUrl, cache : false, crossDomain: true, dataType: "jsonp", success : f ...

Maintaining selected options in select lists while updating model data in Angular

New to Angular and exploring the Product object with Sku objects nested inside. An app allows users to fetch a product, resulting in the Product object being assigned to $scope.product: var app = angular.module('app', []); app.controller(&apos ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

What is the process for transferring the "event" object to the functional form of "this.setState()"?

Utilizing the functional form of this.setState() where a function returning an object is passed. When attempting to bind onChange on an input and using this... onInputChange = event => { this.setState(() => ({ ...this.state, [ev ...

An image appears fractured when placed within a table cell, yet displays perfectly when positioned outside of the table

I am currently facing an issue with loading image files in table cells using jQuery. Here is the code snippet from my View: <table id="personDataTable" border="1"> <tr style="font-size:large; height:auto"> <th width="10 ...

Error Message: Unable to access properties of an undefined object while interacting with an API in a React application

Creating a Weather application in React JS that utilizes the OpenWeatherMapAPI to display dynamic backgrounds based on the API response. I need to access the data at 'data.weather[0].main' which will contain values like 'Clear', ' ...

Is it possible to run an existing NextJS app with API routes on a mobile platform using either Capacitor or Expo?

I have an established NextJS application that heavily relies on Next's API routes. My goal is to transition the current codebase to function in a mobile environment. I've experimented with Capacitor and attempted to export it as a static site, bu ...

Utilizing DIV elements within table cells

Within this particular table, it is not only cell B that contains both a heading and content, but cells A and C as well. My effort to establish the heading and content using DIV elements has been somewhat successful. While I have achieved the desired font ...

Creating visually appealing Jquery-ui tab designs

Trying to customize the jquery tabs, I experimented with styling them to my liking. One thing I did was attempt to reduce the size of the tabs by adding a height:45px; to the UI stylesheet shown below. .ui-tabs-vertical .ui-tabs-nav li { clear: left; ...

What is the best way to position an element on the left side of the navbar without having it animated?

Could someone assist me in placing the Life's Good logo on the left side of the nav bar without applying the animation from the "btn" class? Below is a snippet of my code with an example where I want the logo highlighted in Yellow: * { padding:0; m ...

How can I update the color scheme in styled components based on the active state of the component?

I'm currently working on a react accordion component that requires changing styles based on the active and inactive states. I have successfully set the state and added two props for color and active color. The goal is to change colors when the user cl ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

Struggling to make Reactable work with React Native because of the error "Invariant Violation: View config not found for name input"

After attempting to follow a tutorial on creating tables with React for my React Native app, I consistently encountered errors such as "Invariant Violation: View config not found for name th." Even when trying to run the source code provided in the tutoria ...

Why is the lower right white space left unfilled by the color red?

I'm having issues with using named lines in grid for layout. The red section is not positioning correctly next to the footer, and I can't figure out where I went wrong. * { box-sizing: border-box; margin: 0; padding: 0; } .container { ...