Compare 'e.target' to a jQuery object

dubbelj picture dubbelj · Dec 22, 2011 · Viewed 26k times · Source

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?

Answer

Adam Rackis picture Adam Rackis · Dec 22, 2011

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])