JQuery: If the selected $ (this) element has a parent with the class name 'last'

I need to skip something very important, I used .parent (). parent (). parent () .. etc to traverse the DOM and .next (). next () to traverse the DOM.

I know that this is wrong, and that I need something more reliable, I need a selector that will move from the clicked element of $ (this) down the DOM to see if the element was pressed inside the element with the class "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 a length

 var isWithinLastRow = [amazingSelector].length; 

do something else in this case.

+7
source share
4 answers

Try the following: - 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"); } }); }); 
+16
source

Your question is a little hard to understand. Do you want to check if a click element has an ancestor element with class last , yes?

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

 if ($(this).parents('.last').length) { // element has an ancestor element with the class "last" } 
+4
source

You can use . closeest ()

 var isWithLastRow = $(this).closest('div.last').length 
+1
source

You can do it -

 if($(this).closest(".last").length > 0) { alert("it inside"); } 
+1
source

All Articles