I want to check if an element has a parent/grandparent with a certain class. My code does not work correctly:
JavaScript:
$("body").on("click", function (e) {
if ($(e.target).parents(".granny")) alert("you have a granny");
});
I want to check if an element has a parent/grandparent with a certain class. My code does not work correctly:
JavaScript:
$("body").on("click", function (e) {
if ($(e.target).parents(".granny")) alert("you have a granny");
});
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.
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");
}
});