In jQuery.click()
method it's possible to get the class of element which has fired the event using even.target
. I want to check if the element which has been clicked or one of its parent has some specific class.
<div class="c1"><a href="#" class="c2">Click</a></div>
<script>
$(document).click(function(e){
if($(e.target).hasClass("c1"))
alert("It's C1");
});
</script>
But it always failes because c2
has been clicked. Despite using .parent()
, I'm wondering if there is a way to check the propagation on on-click event.
From what you said is C1 was clicked and you want to know if
You need to see if the element is inside that was clicked.
var target = $(e.target);
if (target.hasClass("c2") || target.find(".c2").length) {
alert("C2 is a child");
}
EDIT, now what you orginally asked is not what you really wanted.
Now if it is a parent it is as simple as
var target = $(e.target);
if (target.hasClass("c1") || target.parents(".c1").length) {
alert("C1 child was clicked");
}
or as Ian pointed out
if (target.closest(".c1").length) {
alert("C1 child was clicked");
}
You can use $(this).hasClass
instead of $(e.target). Also $(this).parent()
will lead to parent of a target
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.