There will be no returns from a function that includes getAttribute operations

I've been trying to display the value of each button, but unfortunately, nothing appears in the console when I click on them.

It seems like I'm overlooking something here and I just can't seem to figure it out.

 const allButtons = document.querySelector("[data-buttons]");

Array.from(allButtons).forEach(button => {
    button.addEventListener("click", () => {
        let userPick = button.getAttribute("[data-pick]");
        console.log(userPick);
    });
});

Your help is greatly appreciated! :)

Answer №1

If you want to iterate directly through the Nodelist retrieved using querySelectorAll

document.querySelectorAll("[data-buttons]").forEach(button => {
  button.addEventListener("click", () => {
    let userSelection = button.getAttribute("data-selection");
    console.log(userSelection);
  });
});
<button data-buttons="1" data-selection="1"> 1</button>
<button data-buttons="2" data-selection="2"> 2</button>
<button data-buttons="3" data-selection="3"> 3</button>

Answer №2

If you have multiple buttons, it is recommended to use querySelectorAll

 const allButtons = document.querySelectorAll("[data-buttons]");

    Array.from(allButtons).forEach(button => {
        button.addEventListener("click", () => {
            let userPick = button.getAttribute("data-pick");
            console.log(userPick);
        });
    });
<button data-buttons="1" data-pick="1"> 1</button>
<button data-buttons="2" data-pick="2"> 2</button>
<button data-buttons="3" data-pick="3"> 3</button>

Answer №3

To access attributes with the prefix data-, you must utilize the dataset object as shown below:

const allButtons = document.querySelectorAll("[data-buttons]");

Array.from(allButtons).forEach(button => {
    button.addEventListener("click", () => {
        let userPick = button.dataset.pick;
        console.log(userPick);
    });
});

Answer №4

Kindly review the code provided below with comments:

// Instead of using "querySelector", opt for "querySelectorAll" to get a NodeList result.
const allButtons = document.querySelectorAll("[data-buttons]");

// You can directly apply "forEach" on a NodeList instance.
allButtons.forEach(button => {
  button.addEventListener("click", ({target}) => {
    // Ensure to provide attribute name without "[]" when using "getAttribute".
    // Here, you can utilize "e.target" instead of "button".
    const userPick = target.getAttribute("data-pick");
    console.log(userPick);
  });
});
<button data-buttons data-pick="A">Button A</button>
<button data-buttons data-pick="B">Button B</button>
<button data-buttons data-pick="C">Button C</button>
<button data-buttons data-pick="D">Button D</button>
<button data-buttons data-pick="E">Button E</button>

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

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: https://i.sstatic.net/ExH4u.png MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(< ...

Modify the property each time I make changes to its value

I have been searching for a solution to my React issue, but so far nothing has worked. I have a component that displays and adds likes, but it only updates after refreshing the page. I've tried using useEffect, but it doesn't seem to fix the prob ...

Populate the ListBox based on the value of the input control in the onKeyUp event

I have a ListBox control <asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem Value="1" Text="XYZ" /> <asp:ListItem Value="0" Text="XYZD" /> <as ...

What could be causing this error with creating an order on Paypal?

Every time I run this code and click the Paypal button, I encounter the following error: Error: "TypeError: Cannot read property 'map' Do you have any clue why this is happening? I am pretty sure that I formatted it correctly. (I replaced MY_C ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

Substitute Symbolic Codes in an Object with Written Text

Here's the structure of the object: { where: { [Symbol(or)]: [ [Object], [Object] ] },hooks: true, rejectOnEmpty: false } When I use JSON.stringify on it, the result is: {"where":{},"hooks":true,"rejectOnEmpty":false} T ...

The step-by-step guide to implementing header filters in autoColumns

I recently started using the tabulator library to create dynamic tables by setting autoColumns:true. Everything was working smoothly until I wanted to add header filters for each column. Despite referring to the documentation, I struggled to find a solutio ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

Is there a way to switch the sorting order on a Bootstrap page using a button without having to refresh the page?

I'm currently working on a template for an app that already exists and would like to add a button to change the sort order of displayed elements on a webpage. The page is styled using Bootstrap 5.3, so I have access to jQuery and other Bootstrap featu ...

Navigate to Angular Link using Scope Data

I have the user's GPS location, which is not fixed. From the frontend, I need to open it as a Google Maps link. <a href="#" ng-click='window.open("https://www.google.com/maps/place/{{data.usergps}}", "_system", "location=yes"); return false;& ...

Having trouble with a basic if-then condition

I'm trying to make a div expand and contract when it's clicked. Here's the code I've used: <div ng-click="disclaimer();" style="height:100px;width:100px;overflow:{{expand}}">Sample Text</div> Essentially, when the user cli ...

What steps should be taken to handle files in the Next JS api?

My goal is to send a docx file to the browser for client preview. I've attempted two methods: const rs = fs.createReadStream(fullPath); res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.docume ...

Is there a reason why this MD Bootstrap Snippet isn't functioning properly?

When zooming out to 25% or beyond, I noticed that the toolbar unexpectedly pops open and refuses to close. How can I prevent this from happening? I asked this question yesterday but unfortunately received only downvotes :( Appreciate any help provided ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level. <blackout v-if="this.popup.currentPopup"></blacko ...

"Create a HTML Form with a Submit Button that Does Not Refresh the Page

I created a form with fields for Name and Email, along with a submit button. The submit button is set to trigger the invite() JavaScript method upon being clicked. <form id="inviteForm" action=""> <div class="modal-body"> ...

Establish a Connection Between Local Mongo Database and Your Application

I have successfully set up a local MongoDB connection with a React, GraphQL application. All configurations are in place and functioning properly as far as I can tell. To visually view my MongoDB databases, I have installed Compass. The content of the Ser ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

Learn how to leverage dynamic imports for a single use case in NextJS

I am currently in the process of developing an App using NextJS and I am looking for a way to display a loading icon while fetching data or loading certain pages. Right now, I have to manually insert the Loading component into each individual component. Fo ...

Rotating around the midpoint of a manipulator in Three.js

Despite asking a similar question recently, I am still struggling to figure out how to properly set the center of a three js control in order for it to rotate as intended. I have come across various examples involving geometry, bounding boxes, pivot points ...