I have a page with a number of links with a class called "myLinkClass". These links can reside in one of two DOM structures:
<div class="divClassA">
<a class="myLinkClass" ...
</div>
or
<div class="divClassB">
<a class="myLinkClass" ...
</div>
I hook up the click event of the links with the class to an event handler with jQuery:
$(document).ready(function () {
$('.myLinkClass').bind('click', function (event) {
//...
});
});
How can I find out if the clicked link is inside a divClassA or a divClassB?
Note that although the links are immeditate childrens to the divs in the examples above, that might not be the case. Also, there might be an arbitrary number of both divClassA and divClassB (not just one of each).
You could check to see if the clicked element has an ancestor with divClassA
. If not, you should be able to assume it's in divClassB
:
$('.myLinkClass').bind('click', function (event) {
if($(this).closest(".divClassA").length) {
//Inside divClassA
}
else {
//Not inside divClassA!
}
});
Here's a working example of the above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With