I have a table dinamically generated by a mySQL query as this:
| title | Published | Delete |
---------------------------------------------
| Review_1 | Yes | click_to_delete |
| Review_2 | Yes | click_to_delete |
| Review_3 | Yes | click_to_delete |
Each table row is builded – for example – with the following code (id is 1 only for example):
<tr>
<td><a class="editlink" id="1" href="#">Review_1</a><td>
<td><input type="checkbox" /></td>
<td><a class="delete_review" id="1" href="#"><img src="remove.png"/></a></td>
</tr>
I would like that when the user clicks – for example – the first link ‘click_to_delete’ an alert pops up saying that his is going to delete the review ‘Review_1’.
So I want to get the TEXT of the Review_1 link when the users clicks the corresponding ‘click_to_delete’.
I tried with the following code:
$(".delete_review").click(function() {
var index = $(".editlink").index(this);
var item_name = $(".editlink").eq(index).text();
alert(item_name);
}
I don’t understand why this line returns correctly the position of the element
var index = $(".editlink").index(this);
while this one does not return the text of the link:
var item_name = $(".editlink").eq(index).text();
of course $(this) is not usefull in this case because the event is not fired by the same element.
You can traverse the DOM tree up to the
tdelement usingclosest(orparent, but bear in mind that it would then break if you happened to add more elements in between) and then usesiblingsandeqto get the first sibling:The
indexmethod returns the index of the element relative to its siblings. In your case, the link has no siblings, so the index should always be 0.