Compare 'e.target' to a jQuery object
Asked Answered
C

5

39

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?

Contend answered 22/12, 2011 at 15:47 Comment(0)
S
45

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])
Sporocyst answered 22/12, 2011 at 15:48 Comment(1)
I like this answer, because it describes why my approach did not work. jQuery returns a collection of items.Contend
P
40

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

Plutocracy answered 22/12, 2011 at 15:49 Comment(1)
if you already have a reference to the element you want to compare against, the following works: $myButton.is(e.target)Koziol
D
0

If you want to match the element that the event is attached to you can use $(this), or if you want to find which element triggered the event use $(event.target).

Below is an example of both of these.

http://jsfiddle.net/Phunky/TbJef/

Unless you're using event delegation these will be the same though and if there the same element.

Domitiladomonic answered 22/12, 2011 at 16:0 Comment(0)
W
0

Obviously using .is() function is the best solution here.

If you find yourself doing such comparison, try to check if it is possible to use embedded jQuery mechanisms like this:

$(element).on("click", ".selector", function() {
    alert("clicked");
});

Second argument in the .on() method is a target selector. When using this construction (read more: http://api.jquery.com/on/#direct-and-delegated-events) there will be no need to make any additional comparisons.

https://jsfiddle.net/m5zysufy/

Whit answered 9/11, 2016 at 9:4 Comment(0)
F
0
$(document).click(function (e) {
  e.stopPropagation();
  var container = $('.dropdown-list').attr('class');
  if ($(e.target).attr('class') == container) {
    $('.dropdown-menu').slideToggle();
  } else {
    $('.header .header-elem .dropdown-nav .dropdown-menu').slideUp();
  }
});
Foxtail answered 4/3, 2021 at 7:15 Comment(1)
Add some explanation to your answerStudley

© 2022 - 2024 — McMap. All rights reserved.