0

I want to check if an element has a parent/grandparent with a certain class. My code does not work correctly:

js fiddle

JavaScript:

$("body").on("click", function (e) {
    if ($(e.target).parents(".granny")) alert("you have a granny");
});
Allan Kimmer Jensen
  • 4,333
  • 2
  • 31
  • 53
user1477955
  • 1,652
  • 8
  • 23
  • 35

2 Answers2

4

if( $(e.target).parents(".granny") ) will always be true since you are checking the jQuery object, which is a truthy value.

Check the length property instead :

if( $(e.target).parents(".granny").length )

When searching for a parent, closest() may be interesting since it is way faster. It doesn't loop through all parents, it stop once it find a match.

While parents doesn't stop until it reach the root of the document, .parents() doesn't include the target itself. That mean that is you click on .granny directly (it become the e.target) while using closest, the alert will pop while parents will not.

Knowing that, you are the only juge on what method you really need.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

When you use closest() it stops once there is a match .

$("body").on("click", function(e){
    if( $(e.target).closest(".granny").length ){
        alert("you have a granny");
    }
});

fiddle

Alexander
  • 12,424
  • 5
  • 59
  • 76
  • 1
    As stated by Frédéric Hamidi in a comment that he deleted on my answer, `.closest` include the element itself while `.parents` doesn't. Technically, if you click on the granny, she doesn't have a granny (she is the granny). OP may not want that. – Karl-André Gagnon Apr 30 '14 at 13:57