Reputation: 1570
In the following structure
<div class="thisNot">
<table style="width:100%" class="thisOneUknow">
<tr>
<th id="imhere">Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
If I'm on the $('#imhere'), How I can find the closest parent with a class and extract that value? In this case get thisOne (always thinking that i'm standing imhere element)
EDIT: the class thisOneOknown is generated automatically, so this changed on every Page Load, so the selector has been capable to find the first parent with class and store/return it . Somethinng like var closestParentClass = $('#imhere').closest(":hasParent()");
Upvotes: 1
Views: 5530
Reputation: 195
$('#imhere').closest('.thisOne');
Update after edited question:
I'm afraid I don't understand what you're asking now, however I'll take a guess. Something like the following should allow you to test each parent up to the DOM root:
var element = $($('.lobster')[6]);
while((element = element.parent()).length){
if(element.is('table')){
break;
}
}
// element variable contains the matched DOM element
Upvotes: 4
Reputation: 317
You can use filter method, try this example I put together for you. I hope that helps you.
$(function() {
var tt= finder('.thisOne','#imhere');
$('.result').append('<div>data found:'+tt.length+'</div>');
// some unknow class
var ss= finder('.thisOne','#imNothere');
$('.result').append('<div>data found:'+ss.length+'</div>');
});
function finder(searchMe, checkMe){
return $(searchMe).filter(function(index) {
return $(this).find(checkMe).length > 0;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thisNot">
<table style="width:100%" class="thisOne">
<tr>
<th id="imhere">Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
<div class="result"></div>
Upvotes: 1