Reputation: 4147
I have a jquery I'm running to get the first < a > tag text, but it seems its getting all of the elements and I'm not sure what I'm doing wrong.
<tr>
<td>
<a>text 1</a>
</td>
<td>
<a>text 2</a>
</td>
<td>
<a>text 3</a>
</td>
<td>
<a>text 4</a>
</td>
<button>click</button>
</tr>
$(button).on('click',function(){
var getText = $(this).closest('tr').next().find('a:first-child');
var getText = $(this).closest('tr').next().find('a:nth-child(1)');//tried this too
})
So the result should be "text 1" for the variable. Right now its returning all < a > tags.
Upvotes: 1
Views: 213
Reputation: 115202
All the a
tags are the first child of it's parent, so get the a
tag within the first td
element. And there is no need to use next()
method in case you want to get the a
tag within the same tr
element.
var getText = $(this).closest('tr').find('td:first-child a');
FYI : Your markup is not valid since you can't use button
tag as the child within the tr
tag, the only allowed tags are td
and th
. So move the button
tag to any of the td
or add a new td
element.
Upvotes: 2
Reputation: 18113
First off, the button should be in a <td>
as well, since it's no legitimate child of a <tr>
.
Then, you want to find the table row. closest(tr)
travels up the tree and finds that row.
You use next()
, which will select the next row... but you don't want that. So delete it.
Then you want to find the first table cell and find the anchor inside the cell (so not the first anchor). We do that with find(td:first-child a)
.
Last... with $(this).closest('tr').find('td:first-child a')
you get the object (element). If you want the text inside it, use the text()
-function.
All together:
$('button').on('click', function() {
var getText = $(this).closest('tr').find('td:first-child a').text();
console.log(getText);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<a>text 1</a>
</td>
<td>
<a>text 2</a>
</td>
<td>
<a>text 3</a>
</td>
<td>
<a>text 4</a>
</td>
<td>
<button>click</button>
</td>
</tr>
</table>
Upvotes: 2
Reputation: 1712
Try the foloowing:
$(button).on('click',function(){
var getText = $(this).closest('tr').next().find('td:first a').html();
});
Upvotes: 0
Reputation: 339
You have to add .text() function like below
$(button).on('click',function(){
var getText = $(this).closest('tr').next().find('a:first-child').text();
var getText = $(this).closest('tr').next().find('a:nth-child(1)').text();//tried this too
})
Upvotes: 0
Reputation: 305
use a:nth-of-type(1)
as selector problem will be solved
as
('a:nth-of-type(1)').text()
Upvotes: 0