ClickEvent (or element selector) is experiencing functionality issues

I'm currently working on creating a small calculator using HTML, CSS, and JS.

However, I'm facing an issue with selecting buttons of the calculator from the HTML script and adding EventListeners to them. Here is a snippet of my HTML code:

`<table class="table1">
            <tr>
                <td id="n-1">1</td>
                <td id="n-2">2</td>
                <td id="n-3">3</td>
            </tr>
            <tr>
                <td id="n-4">4</td>
                <td id="n-5">5</td>
                <td id="n-6">6</td>
            </tr>
            <tr>
                <td id="n-7">7</td>
                <td id="n-8">8</td>
                <td id="n-9">9</td>
            </tr>
        </table>`

Below is the event function I have implemented:

document.querySelector(.table1 td).addEventListener('click',function(){
        console.log('It works');
        var z = this.value;
        console.log(z);
    });

Oddly enough, I am only able to see the console output when clicking on the first cell in the table (1). For some reason, it doesn't work when I click on other cells like 3 or 7.

If you have any insights or solutions to this problem, I would greatly appreciate it. Thank you!

Answer №1

querySelector() will only retrieve a single element, such as the first td within the .table1 class. To apply the event listener to all td elements, you should utilize querySelectorAll():

document.querySelectorAll('.table1 td').addEventListener('click',function(){
    .... // Insert the rest of your code here
});

For more information, visit: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

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

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Allow the javascript callback function to complete before proceeding

Utilizing the Google Storage API, I am saving a file in a GCP bucket within an asynchronous function. My objective is to wait until I receive an error or success callback before proceeding with the subsequent lines of code. However, I am encountering the i ...

Cycle through images that are dynamically generated from retrieved data

Although I have a functional solution for this issue, it feels messy and not the ideal way to handle it in Vue. The challenge is fetching data from a backend related to a "Vendor" entity, which includes photos that need to be displayed on the page. The go ...

Guide on incorporating JSON information into an HTML table

Currently, I am retrieving data that needs to be added to an HTML table once it is received. I have attempted some methods, but I am unable to dynamically add the data after the page has loaded. I aim to accomplish this using either JavaScript or jQuery. ...

Enhance your website with a stylish CSS jQuery menu that lets you toggle, slide

If you're curious about the code, take a look here! Here are some of the issues I'm facing: The div doesn't toggle to hide when clicked on itself, only when another one is clicked. (UPDATE: it actually won't toggle at all) When t ...

Halt the Changing of Button and Typography Styles with React Router and MUI

I am currently working on a component that I want to make clickable. However, when I wrap them in a <Link> element (from react-router-dom) or set component={Link} to="" on them, all the text inside them automatically becomes hyperlinks. For ...

Updating the PHP form to include functionality for a reset button and adjusting the logic for

Having some difficulties with my PHP form. I created a simple form that consists of the following logic: if (isset($_POST['submit'])) { } elseif (isset($_POST['confirm'])) { } else { } The form includes a submit button, followed by a ...

Storing the outcome of a connection in a variable using Node.js

I am facing an issue with saving a function return in a const so that I can utilize the information outside of the function scope. Below is a snippet of code to better explain my problem: const express = require('express') const app = express() ...

Find the div element that wraps around the currently selected radio button

Take a look at this code snippet: <div class="paymentOption"> <input type="radio" name="paymentOption" value="1" /> <span class="marginLeft10">1-time payment using a different credit card</span> </div> Is it feasible ...

Adding information into material-ui dropdown using React JS

I could use some assistance with populating data into a Dropdown using material-ui in React. I am new to React and unsure about how to achieve this. I know that I can pass props to the dropdown, but it's not very clear to me. Here is my current code: ...

Arranging data in Ember: sorting an array based on several properties in different directions

Is it possible to sort a collection of Ember Models by multiple properties, where each property can be sorted in different directions? For example, sorting by property a in ascending order and by property b in descending order? Update I attempted to use ...

Utilize Meteor's ability to import async functions for seamless integration into method calls

Encountering an issue with this Meteor app where the error TypeError: vinXXX is not a function occurs when attempting to call an exported async function named "vinXXX" from within a method call in a sibling folder, which has been imported in the methods f ...

The user removal process is not functioning properly

I'm encountering an issue in my Angularfire project while trying to remove a user. The email and password are being passed correctly, but the method responsible for user removal isn't getting executed. Below is the snippet of code from my Authent ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

Attempting to create a dynamic grid layout utilizing CSS to ensure optimal responsiveness

I am working on creating a webpage layout similar to the one in the link below: The maximum width for the layout is set to 1600px. However, I am facing challenges in making it fully responsive. This is because all the boxes are given widths in percentages ...