Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 924
Iamsamstimpson Avatar asked Jun 12 '13 15:06

Iamsamstimpson


2 Answers

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");
       }
    });
});
like image 60
Aditya Singh Avatar answered Oct 13 '22 17:10

Aditya Singh


You can do this -

if($(this).closest(".last").length > 0) {
   alert("it's inside");
}
like image 41
Mohammad Adil Avatar answered Oct 13 '22 16:10

Mohammad Adil