Valkyriee Valkyriee - 6 days ago 6
jQuery Question

How to get id after filtering element's exact text using jquery

I am trying to get the

id
value of the
td
element within my
table
but only if its exactly "18:00" for example. I used
:contains
but its not exactly same
td
, so I went with
filter
as other question I read suggested and came up with this but it does not work. It returns
undefined
. Does anyone have a better solution?



$(document).ready(function() {
var spa = $('#mainTable').filter(function() {
return $(this).text() === "19:30";
}).attr('id');
alert(spa);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mainTable">
<thead>
<tr>
<th>Arrival Hours</th>
</tr>
</thead>
<tbody>
<tr>
<td id="test1">19:30</td>
</tr>
<tr>
<td id="test2">20:00</td>
</tr>
<tr>
<td id="test3">20:30</td>
</tr>
</tbody>
</table>




Answer

You need to iterate td element and fetch its id property. thus change the selector.

   var spa = $('#mainTable td').filter(function() {
        return $(this).text() === "19:30";
   }).attr('id');

$(document).ready(function() {
  var spa = $('#mainTable tbody td').filter(function() {
    return $(this).text() === "19:30";
  }).attr('id');
  alert(spa);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mainTable">
  <thead>
    <tr>
      <th>Arrival Hours</th>
    </tr>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="test1">19:30</td>
    </tr>
    <tr>
      <td id="test2">20:00</td>
    </tr>
    <tr>
      <td id="test3">20:30</td>
    </tr>
  </tbody>
</table>

Comments