Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 'e.target' to a jQuery object

What I want to do:

( clickedObject === someDiv ) //returns true or false 

What I tried

( $(e.target) === $('.selector') ); //returns a false negative. 

My workaround

( $(e.target).attr('class') === $('.selector').attr('class') ); //works as intended, not so clean though. 

What is the right way to compare the object I clicked to an object in the DOM?

like image 982
dubbelj Avatar asked Dec 22 '11 15:12

dubbelj


People also ask

What is E target jQuery?

Definition and Usage. The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.

What is E target in Javascript?

When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target. So, the target property of that event object refers to the event emitter.

How do I know which DIV is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.


2 Answers

To check if e.target has this class you can use the hasClass function.

if ($(e.target).hasClass("selector")) 

Or, if you really want to compare objects, note that jQuery selectors return a collection of items, so I think you'll want

if (e.target === $('.selector')[0]) 
like image 163
Adam Rackis Avatar answered Oct 04 '22 20:10

Adam Rackis


You're close. Use .is() instead:

if($(e.target).is('.selector')) {     // Your code } 

The trick here is that you wrap e.target in a jQuery object to allow it access to all the useful jQuery methods.

If you're just seeing whether e.target has a certain class, try using .hasClass() in place of .is():

if($(e.target).hasClass('selector')) {     // Your code } 

Either method works, although .hasClass() is a little clearer as to what the code does, and is faster than using .is()

like image 21
Bojangles Avatar answered Oct 04 '22 22:10

Bojangles