conan conan - 3 months ago 15
HTML Question

what is wrong with my code, trying to get first element text jquery?

Look at my code, I want to make it like that when a user click the table tr, I will get the first td text, so jquery I use first() and then text(), but it echo out both td 1 and td apple. I only want to get the first td text, what did I do wrong? Appreciate.



var gridtable = $('.gridtable');

gridtable.click(function(){
var name = $(this).first().text();
alert('name');
})

<tr class="gridtable">
<td>1</td>
<td >apple</td>
</tr>
<tr class="gridtable">
<td>2</td>
<td >banana</td>
</tr>




Answer

Inside handler this refers to the clicked tr applying first() method will retrieve the same tr itself . Instead, you need to filter out the nested td element. You can use the :first pseudo-class selector to get the first element.

var gridtable = $('.gridtable:first');
gridtable.click(function(){
    // get the first element within the context
    var name = $('td:first', this).text();
    alert(name);
});

var gridtable = $('.gridtable');

gridtable.click(function() {
  var name = $('td:first',this).text();
  alert(name);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="gridtable">
    <td>1</td>
    <td>apple</td>
  </tr>
  <tr class="gridtable">
    <td>2</td>
    <td>banana</td>
  </tr>
</table>