Reputation: 2726
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).
Upvotes: 6
Views: 90
Reputation: 7675
HTML:
<div class="divClassB">
<a class="myLinkClass">click1</a>
</div>
<div class="divClassA">
<a class="myLinkClass">click2</a>
</div>
jQuery:
$('.myLinkClass').bind('click', function (event) {
alert($(this).parent().attr('class'));
});
In this code alert will show the class name of parent div. If you want to use this name in condition then try with the following (if you have more than 2 <a>
tag):
$('.myLinkClass').bind('click', function (event) {
switch($(this).parent().attr('class'))
{
case 'divClassB':
//do your stuff
break;
case 'divClassA':
//do your stuff
break;
}
});
Upvotes: 0
Reputation: 6408
could be
$(document).ready(function () {
$('.myLinkClass').bind('click', function (event) {
if($(this).parents('.divClassB').length) {
//parent has divClassB
}
});
});
however, if you're trying to create different events for different "divClasses", something like this might be more adequate:
$(document).ready(function () {
$('.divClassA .myLinkClass').bind('click', function (event) {
//in divClassA
});
$('.divClassB .myLinkClass').bind('click', function (event) {
//in divClassB
});
});
Upvotes: 1
Reputation: 360572
$('.myLinkClass').bind('click', function (event) {
if $(this).parent('div.divClassB') {
... it's in a classB ...
}
});
Upvotes: 0
Reputation: 3144
you can try like this :
var parent = $(this).parent;
var parentName = parent.attr('class');
Upvotes: 0
Reputation: 165951
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.
Upvotes: 3