Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding "position" in DOM of clicked link

Tags:

jquery

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).

like image 534
haagel Avatar asked Nov 24 '11 14:11

haagel


1 Answers

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.

like image 66
James Allardice Avatar answered Oct 18 '22 20:10

James Allardice