khollenbeck
khollenbeck

Reputation: 16157

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.

Upvotes: 4

Views: 17943

Answers (5)

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

First Select all possible DOM Elements

 var lastSelectedElement = null

    $(document).ready(function(){
       $("*").live("click",function(){
       lastSelectedElement = $(this);
       myFunction($(this));
      });
    });

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

than you could play with lastSelectedElement by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");

Upvotes: 0

Zbigniew
Zbigniew

Reputation: 27614

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

Upvotes: 1

Dan Barzilay
Dan Barzilay

Reputation: 4993

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


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

    console.log(lastID);
}

Upvotes: 1

David Thomas
David Thomas

Reputation: 253456

In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:

var lastClickedElement = $.lastClicked,
    lastClickedElementClassNames = lastClickedElement.className;

This does return the full list of all the classes of the element though.

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191789

A couple of ways come to mind:

$(".button").click(myFunction);

Should work with the above myFunction.


$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
   var lastID;
   lastID = $elem.attr('id');
   $.data('lastID', lastID);
}

Upvotes: 1

Related Questions