Skip to content
Advertisement

How can I find the element clicked on inside a jQuery handler?

I’m trying to do a specific action on the clicked element if an argument is passed in the on click method in jQuery. When I try to access this it’s referencing the entire window instead of the clicked on element. How would I access the clicked on element in the handler?

Here’s the code I’m using:

JavaScript

I set up an example on jsbin here. Any help would be appreciated.

Advertisement

Answer

There are several ways to do this.

JQUERY WAY:

Within your jquery click event handlers you have the event object. It has a property called target which is what you’re looking for.

Change this: $this.addClass("one");

To this: $(event.target).addClass("one");

You can also do this: event.target.className = "one"

And do for “two” as well obviously…

VANILLA WAY:

You can just pass in an extra argument representing your clicked element.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement