Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to get the class or id of last clicked element?

I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...

HTML

<a href="" class="button">Button</a>

JQUERY

$('.button').click(function () {
          myFuntion();
});

function myFunction (e) {
 e = e || event;
 $.lastClicked = e.target || e.srcElement;

 var lastClickedElement = $.lastClicked;
 console.log(lastClickedElement);

}

This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.

I have also tried using this solution but couldn't get it to work with my code.

$('.button').click(function () {
  myFuntion();
});


function myFunction(){
    var lastID;
    lastID = $(this).attr("id");

    console.log(lastID);
}

When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.

like image 641
Kris Hollenbeck Avatar asked Sep 10 '25 23:09

Kris Hollenbeck


1 Answers

You can pass clicked element as parameter to your function:

$('.button').click(function () {
    myFunction(this);
});

function myFunction(element) {
    console.log(element);
    console.log(element.id);
    console.log($(element).attr("class"));
}

UPDATE added jsfiddle

like image 196
Zbigniew Avatar answered Sep 13 '25 14:09

Zbigniew