jQuery: If the selected element $(this) has a parent with a classname of 'last'

Iamsamstimpson picture Iamsamstimpson · Jun 12, 2013 · Viewed 21.8k times · Source

I must be missing something quite important, I have been using .parent().parent().parent().. etc to traverse down the DOM and .next().next() to traverse up the DOM.

I know this is wrong and that I need something more reliable, I need a selector that will traverse from the clicked element $(this) down the DOM to see if the element clicked is within an element with a class of "last".

div.last > div > table > tr > td > a[THE ITEM CLICKED is in the element last]

and

div > div > table > tr > td > a[THE ITEM CLICKED is not in the element last]

then if the result has length

var isWithinLastRow = [amazingSelector].length;

do something else in this case.

Answer

Aditya Singh picture Aditya Singh · Jun 12, 2013

Try this out:-http://jsfiddle.net/adiioo7/PjSV7/

HTML:-

<div class="last">
    <div>
        <table>
            <tr>
                <td>
                    <a>Test</a>
                </td>
            </tr>
        </table>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <td>
                    <a>Test</a>
                </td>
            </tr>
        </table>
    </div>
</div>

JS:-

jQuery(function($){
    $("a").on("click",function(){
       if($(this).closest(".last").length>0)
       {
           alert("Clicked anchor with div parent class as last");
       }
    });
});