Reputation: 7345
<div id="m101">
<table class="tablec" width="80%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><a href="#"><span class="name">My Name</span></a></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><a href="#"><span class="clickme">clickme</span></a></td>
</tr>
</table>
</div>
Which selector should I use to capture the content of "name" if clickme is clicked? There are more than one of those tables with the same classes, but the surrounding divs are unique. The name is different each time.
I've been experimenting the with parent, parents and closest functions so far without luck.
$(".clickme").click(function(){
var name = $(this).closest('.name').text();
alert(name);
});
Upvotes: 0
Views: 71
Reputation: 3683
Simplest of answers -
$(document).ready(function(){
$('.clickme').click(function(){
var getName = $('.name').text();
alert(getName);
});
});
Upvotes: 0
Reputation: 10565
This did the work for me
function() {
$(".clickme").click(
function(e) {
alert($(this).parents("div").find(".name").html());
}
);
}
Upvotes: 1
Reputation: 33163
You can traverse the tree up until you hit a <table>
:
var name = $( this ).closest( 'table' ).find( '.name' ).text();
Upvotes: 1
Reputation: 7280
You are not able to select the .name
using closest()
as it is not an ancestor. You would need to select a common ancestor e.g. the table
and then work back down the tree to the .name
element.
$(".clickme").click(function(){
var table = $(this).closest("table");
var name = table.find('.name').text();
alert(name);
});
You could have this in a single line using
$(".clickme").click(function(){
var name = $(this).closest("table").find('.name').text();
alert(name);
});
Upvotes: 1
Reputation: 4623
Would something like this do the trick?
$(".name", $(this).closest("div")).text()
Working example here: http://jsfiddle.net/44re8/
Upvotes: 2