user3730179 user3730179 - 11 months ago 46
Javascript Question

getting the element's id from on click with (this)

To initiate the onclick event, I have this

[], (btnAddVendorDropDown) => {
btnAddVendorDropDown.addEventListener('click', onAddVendorDropDownClick, false);

The function is

function onAddVendorDropDownClick(e) {

addNewClass(modal, 'is-active');
addNewClass(modalAddVendorDropDown, 'is-active');

const test = $(this).attr('id');
return test;

So what I'm trying to do is when a user clicks
, the function
is called. I need to grab the id from the element. When I do
of the element attribute
from inside the function, I get exactly what I need. The problem I'm running into is when I try to grab it from outside the function, I keep getting
. I don't understand how I can grab the id once it calls this function from outside this function.

I tried this

var num = onAddVendorDropDownClick();
console.log("the function return is " + num);

Which is what shows

Answer Source

this related directly to the caller's scope. This means that without "binding" a scope to your event handler, this is going to refer to your main application scope, and not the scope that jquery passes as you chain functions.

You can either wrap the event object's target:

function onClickHandler(e) {

Or you can use $(this) within the jquery context of a click handler:

$('#my-button').on('click', function(e) { $(this).attr('id'); });

The last example works because it is occurring inside a JQuery closure, so it retains the scope from the previous function. Outside of a closure, this means something else.