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

24,214

Solution 1

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");
       }
    });
});

Solution 2

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"
}

Solution 3

You can do this -

if($(this).closest(".last").length > 0) {
   alert("it's inside");
}

Solution 4

You can use .closest()

var isWithLastRow = $(this).closest('div.last').length
Share:
24,214
Iamsamstimpson
Author by

Iamsamstimpson

/-/CURRENTLY/-/ I'm a full time web-developer living in London, UK. /-/WHY/-/ I have a passion for web development and all aspects that surround it. I'm forever reading, listening and most importantly doing.. /-/BACKGROUND/-/ My background is in the Arts and Media - In school I enjoyed Graphic Product Design and Art - I was also very strong in Science... later I studied Software Systems for the Arts and Media (Computer Science) at Degree Level achieving a 1st class hons, before that I was a strange kid taking computers apart, installing obscure operating systems and drawing a lot. http://teamtreehouse.com/smoop

Updated on July 09, 2022

Comments

  • Iamsamstimpson
    Iamsamstimpson almost 2 years

    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.