Retrieve the element that was clicked by targeting its class name using JavaScript

Unfortunately, I couldn't create this example in JSFiddle as it's currently in read-only mode.

My goal is to identify the specific element that was clicked based on a given class.

var button = document.getElementsByClassName("mybutton");
button.onclick = function() {
    //How can I pinpoint the exact button that was clicked?
};

 

<button class="myclass">Button 1</button>
<button class="myclass">Button 2</button>

Please refrain from providing jQuery solutions as they are not an option in this case.

Answer №1

Forget about using document.getElementByClassName, switch to document.getElementsByClassName.

Do you see the distinction now?

It's a simple mistake to make:

document.getElementByClassName
document.getElementsByClassName
                   ^

The former is nonexistent unless specifically defined, while the latter is functional in current web browsers. getElementsByClassName will provide a node list that requires iteration for attaching event listeners to each node.

var i,
    l,
    buttons,
    button;

function clickHandler(e) {
    console.log(this);//indicates the clicked button
}
buttons = document.getElementsByClassName('mybutton');
for (i = 0, l = buttons.length; i < l; i++) {
    button = buttons[i];
    button.onclick = clickHandler;
}

Answer №2

Your event handler will receive a reference to the event as its first argument

var btn = document.querySelector(".myBtn");
btn.onclick = function(event) {
    //event.target is a reference to the button that was clicked
};

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

I'm attempting to install the "firebase" package using npm, but I keep encountering a python-related error message during the installation process

I am experiencing difficulties while attempting to install the firebase package in a local expo-managed project. Unfortunately, I keep receiving the following error message... Here is the error message that I am encountering I have already tried using "e ...

Error: Unexpected identifier in jQuery ajax line

I'm currently encountering an issue with my jQuery ajax call that's throwing an "Uncaught SyntaxError: Unexpected identifier" error at line 3. For confidentiality reasons, I have omitted the original URL. However, even after removing the csrHost ...

Adding JSON data to a table with the keys in the first row is a simple process that can be achieved

Previously, I have created tables with XML formatted results and JSON data in the "key: data" format. To access the data, I would use syntax like results.heading1 and then map the data into a table by matching the key with the data. Now, a new client is o ...

What is the method for obtaining the input value of an input type number in HTML?

Within my form, there is a number field where users can input scores: <input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please input a score from 0-10 ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

Utilizing jQuery to send multiple values via an ajax request

I am looking to modify this script to send multiple values using AJAX instead of just a single value. files.php $(".search_button").click(function() { var search_word = $("#search_box").val(); var dataString = 'search_word='+ search_word ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

Javascript - Could anyone provide a detailed explanation of the functionality of this code snippet?

Ever since joining a new company 9 months ago, I've been encountering this line of code in JavaScript. It seems to work fine and I've been incorporating it into my coding style to align with the previous developers. However, I'm not entirely ...

Executing synchronous animations in Jquery with callback logic

My jQuery plugins often rely on user-defined callbacks, like in the example below: (function($) { $.fn.myplugin = function(options) { var s = $.extend({}, options), $this = $(this); if (typeof s['initCallback'] = ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Transitioning from webpack to vite with Vue.js for a Chrome extension development project

I am currently developing a Chrome extension using Vue.js. I have a project ready to start with, but it is set up with webpack. Within webpack, I have multiple entry points that result in the generation of HTML files and others with JavaScript only. Whil ...

I require assistance in understanding how to successfully implement ParseINT with (row.find)

enter image description hereHow To Utilize ParseINT Using row.find(). I Attempted This Code But It Doesn't Work. This is My Code : function update_qty() { var row2 = $(this).parents('.item-row'); var price2 = row2.find(parseInt($ ...

The Material UI slider vanishes the moment I drag it towards the initial element

After moving the Material UI Slider to the initial position, it suddenly vanishes. via GIPHY I've spent 5 hours attempting to locate the source of the issue but have not had any success. ...

Is there a way to prevent on-click errors in ReactJS that someone can share with me?

The onclick listener was expected to be a function, but instead received a value of string type. getListener@http://localhost:3000/static/js/bundle.js:18256:15 accumulateSinglePhaseListeners@http://localhost:3000/static/js/bundle.js:22846:39 <button on ...

What is the best way to retrieve the parent element in jQuery when you already have the child element selected

I am working with jQuery Mobile, which automatically generates a lot of the DOM structure. The challenge I am facing is removing radio buttons without having an id for the parent div due to the HTML construction in jQuery Mobile. While I can easily targe ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

Tips for utilizing jQuery to display images similar to videos

Are there any plugins available that can create a video-like effect on images by incorporating scroll, pan, tilt, zoom (in/out) transitions for a few seconds before fading to the next image? I've searched but haven't found anything quite like thi ...