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

Utilizing CSS and javascript to display position indicators on a map

I need help creating a basic webpage with the following functionality: The page will contain a map as a background image in a div, with clickable images placed on top (each within its own div). When these images are clicked, markers should appear or disap ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

How can I identify where a Mesh and Particle System intersect in Three.js?

I have a unique setup where I have a particle system utilizing sprites, housed in an Object3D akin to the "interactive / points" example from three.js. Additionally, I have a simple sphere mesh that tracks my cursor's movements. Check out the example ...

Oops! An error occurred: Uncaught promise in TypeError - Unable to map property 'map' as it is undefined

Encountering an error specifically when attempting to return a value from the catch block. Wondering if there is a mistake in the approach. Why is it not possible to return an observable from catch? .ts getMyTopic() { return this.topicSer.getMyTopi ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention: abstract class Base { public _obj = { name: 'Test' } print1() { console.log(this._obj) } print2() { console.log(this) } } class Child extends Base { print2( ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

Tips for splitting JSON objects into individual arrays in React

I'm currently tackling a project that requires me to extract 2 JSON objects into separate arrays for use within the application. I want this process to be dynamic, as there may be varying numbers of objects inside the JSON array in the future - potent ...

Executing a snippet of Bootstrap 5 code under specific circumstances

I need to execute different code blocks based on the window width. When the width is 500px or more, I want to run a specific block of code, and when it's 499px or less, I need another block of code to run. How can I achieve this? For widths of 500px ...

Puppeteer Alert: Unable to Locate Node for specified selector

When using Puppeteer to interact with an input element on a requested URL, I encountered an issue. First, I entered a quantity like this: await page.type('#bidamount_temp', bidAmount); However, when trying to click on the following button after ...

Issue between Promise and EventEmitter causing race conditions in ExpressJS

Currently, I am working on a NodeJS/Express web application where users can upload files that are then parsed using the connect-busboy module and saved to a database with Sequelize. Once the data is stored, I aim to redirect the user to a specific page. Ho ...

Leveraging spread syntax and styling for array string interpolation in JavaScript

Imagine I have an array such as [1,2,3] and my goal is to insert its values into a string format like: the values are (?, ?, ?) Can anyone suggest a simple solution for this? I am aware of the spread operator ...[1,2,3], and it's feasible to conver ...

Showing information in a CodeIgniter view with a formatted table

Hi there, I'm currently facing an issue with sorting the correct <td> to display subject results for students. We have a total of 11 subjects offered in the school and senior students are supposed to take 8 subjects, as 4 of them are electives a ...

Using TypeScript to pass objects to an arrow function

Issue at Hand: How do I successfully transfer an object from a parent component to a child component that is derived from the same interface? I am currently facing difficulties in rendering a list of tasks by looping through a list of task objects. The ma ...

Encountering a situation where an empty object is received while attempting to send a

While using Postman to make a request to the API I created for Social Media Application that involves following and followers functionality, I noticed that I am receiving an empty object: {}. However, upon inspection, everything seems to be correct on my e ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

When bootstrap buttons are displayed inside a Vue component, there should be no spacing between them

Is this issue specific to the vue-loader or is it more related to webpack builds in general? Consider a basic HTML page with Bootstrap 4 loaded and two buttons added: <button type="button" class="btn btn-primary">Primary</button> <button t ...

jQuery search and filter functionality ineffective for unordered list of states and cities

CONTEXT: I am aiming to display a list of States initially. There are two options: either clicking on a state will reveal the respective cities, or using the search box will filter cities across all states - clearing the search will hide everything. ISSU ...