Discovering the element's ID upon clicking a button using Mootools (version 1.1)

There are multiple links with random ids as shown below:

<a href="#" class="remove_pid" id="pid_123">Remove 123</a>
<a href="#" class="remove_pid" id="pid_234">Remove 234</a>
<a href="#" class="remove_pid" id="pid_567">Remove 567</a>
<a href="#" class="remove_pid" id="pid_890">Remove 890</a>

An event handler has been set up like this:

$$('.remove_pid').addEvents({
   'click': removePid
});

which triggers the following function:

function removePid(event)
{
    alert('How can I retrieve the element id???');
}

The main query is how to retrieve the element id within the removePid() function.

UPDATE:

@Aishwar, event.target.id appears to work in a specific scenario, but not in my case

<a href="#" class="remove_pid"><img src="/123.jpg" id="pid_123"></a>

UPDATE 2:

Initially overlooked, the content is an image instead of the text "Remove 123" as illustrated below:

<a href="#" class="remove_pid" id="pid_123"><img src="/123.jpg"></a>

Therefore, appreciation to @Dimitra for bringing it to attention. The downvote was unexpected, but I acknowledge its legitimacy.

Answer №1

My knowledge with mootools is limited, however I believe the following code snippet in the removePid function may work:

var obj = event.srcElement || event.target;
obj.id // represents the id of the element, where obj is the actual DOM element

Answer №2

After reviewing the changes made in the latest update:

http://www.jsfiddle.net/dimitar/Sr8LC/

$$('.remove_pid').addEvents({
    'click': function(e) {
        new Event(e).stop();
        var id = this.getProperty("id");
        alert(id);
        alert(id.replace("pid_", ""));
    }
});

In order to implement a named function and maintain the event:

var removeProduct = function(e) {
    new Event(e).stop();
    var id = this.getProperty("id");
    alert(id);
    alert(id.replace("pid_", ""));
};

$$('a.remove_pid').each(function(el) {
    el.addEvents({
        'click': removeProduct.bind(el)
    });
});

Both functions will have this referring to the triggering element (the anchor), allowing you to access its properties. Additionally, this.getFirst() can be used to reference the image (if needed).

Answer №3

Here's the solution I came up with:

const findElementById = (event) => {
    //alert('yo what is my element id???');
    $(event.target).closest('a').attr('id');
}

Tested and verified on Firefox 3.6

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

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Issue encountered while attempting to attach an event listener to an element within a class

Upon running the code, I encountered an error message that reads: Uncaught TypeError: this.startButton.addEventListener is not a function and I'm unsure of how to resolve it. Although I can successfully console.log the button inside the class, adding ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

I am attempting to push notifications to a particular device using Firebase cloud functions

I am currently developing a chat app using Flutter, and I am attempting to send notifications to specific devices using a cloud function. The goal is for a user to send a message to a friend and have the friend receive a notification with the message. Howe ...

React encountered an expression when it was looking for either an assignment or function call

I'm facing an issue while trying to display the data retrieved from my database. Instead of the expected output, I am getting an error message - Failed to compile. ./src/components/list-pets.component.js Line 38:5: Expected an assignment or function ...

I am unable to update an array within my component using useEffect

Encountered two problems, firstly while attempting to pass an array of objects from a parent component to a child component, facing difficulties as shown below: function DropdownSome ({options, placeholder, someNum}) { const [value, setValue] = useState ...

Tips for importing a PDF file and storing it in your database

I have a project using Angular 7, .NET Framework, and MongoDB where I am creating user profiles. One of the requirements is to allow users to optionally upload a PDF file along with their other information. This is what I have implemented so far: <labe ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

What are the benefits of adding member functions to the data structures of React.js store?

Using React.js and Typescript, I store plain Javascript objects in the React.js store. These objects are sometimes received from the server without any member functions, but I wish to add functions for better organization. Instead of having to rely on exte ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

The map function is malfunctioning when trying to query data from MongoDB

I have multiple mongodb documents structured like this {'_id':'1', 'year':2020, 'season':'Summer', 'status':'Over'}, {'_id':'2', 'year':2020, 'se ...

Creating a div resizing function using only JavaScript is a fun and useful project to tackle

Seeking help to create a div resizer using only pure JavaScript as jQuery is restricted. The current functionality works, but breaks when the position of the slider-div is not set to absolute. Any solutions to fix this issue would be greatly appreciated. ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

How can I create 3 conditions in an AJAX request to verify a user's ID?

I am trying to create 3 conditions in Ajax to check when creating a new user id. It works for 2 conditions (username can be used and username is already in use), but I encounter a problem when the user leaves the username field empty, and it still displays ...

It appears that the pixel sizes are different than what was originally designed

In my project, I have a header panel where the burger button is designed with a width of 32px and height of 24px. .header { display: flex; font-weight: bold; font-size: 50px; height: 100px; border: 1px solid black; position: relativ ...

JavaScript closures and the misinterpretation of returning values

function generateUniqueCelebrityIDs(celebrities) { var i; var uniqueID = 100; for (i = 0; i < celebrities.length; i++) { celebrities[i]["id"] = function () { return uniqueID + i; }; }; return celebrities; ...

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

What could be causing the block to fail in the event of an AJAX request?

I have encountered an issue with my PHP file and AJAX setup. The if block in my code is working properly, but the else block seems to be not functioning as expected. Even after changing the condition from data!= null to data== null, the problem persists wh ...

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

How can the total price for a shopping cart be computed in React/Redux?

After extensive searches on Google and SO, I'm still coming up empty-handed when it comes to calculating the total price of items in a cart. Many tutorials stop at basic cart functionalities like "Add item to cart" or "increase/decrease quantity", but ...