12

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.

Iamsamstimpson
  • 1,359
  • 2
  • 17
  • 32
  • 2
    Try `$(this).closest('div.last')` Also.. `.parent()` and `.next()` are not the related(meaning not exact opposite). `.next()` is to fetch the next sibling and `.parent` is to go straight to the parent. The exact opposite of `.next` is `.prev`. – Selvakumar Arumugam Jun 12 '13 at 15:05

4 Answers4

22

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");
       }
    });
});
Aditya Singh
  • 9,512
  • 5
  • 32
  • 55
9

Your question is a little hard to understand. You want to check if the element clicked has an ancestor element with the class last, yes?

If so, you can do so with $.fn.parents:

if ($(this).parents('.last').length) {
    // element has an ancestor element with the class "last"
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 1
    From the comparison between `parents` and `closest` in the [latter's API](https://api.jquery.com/closest/) it looks like `closest` is faster because it stops at the first match. – Paul Sep 10 '15 at 14:03
3

You can do this -

if($(this).closest(".last").length > 0) {
   alert("it's inside");
}
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

You can use .closest()

var isWithLastRow = $(this).closest('div.last').length
wirey00
  • 33,517
  • 7
  • 54
  • 65