Kerem Çakır
Kerem Çakır

Reputation: 401

How can I access value in table

<tbody>
<tr>
    <td><span style="">Price</span></td>
    <td><span style="">:</span></td>
    <td><span style="">660</span></td>
</tr>
<tr>
    <td><span style="">Date</span></td>
    <td><span style="">:</span></td>
    <td><span style="">15.11.1988</span></td>
</tr>
<tr>
    <td><span style="">No</span></td>
    <td><span style="">:</span></td>
    <td><span style="">48961887292</span></td>
</tr>
<tr>
    <td><span style="">Phone</span></td>
    <td><span style="">:</span></td>
    <td><span style="">9005312359188</span></td>
</tr>
</tbody>

There is a table in a site. I want to take phone number in the table. The row of phone sometimes can be third or three or first, and the phone row has no ID. How can I get that phone number with jQuery?

Upvotes: 1

Views: 52

Answers (2)

Phani Kumar M
Phani Kumar M

Reputation: 4590

Assuming the td contains the text Phone. Using query selectors, you can find all td's that contain text Phone, then find the last sibling to get the phone number.

$(function () {
  $("table tr td:contains('Phone')").each(function () {
    console.log($(this).siblings(":last").text());
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<table>
  <tbody>
    <tr>
      <td><span style="">Price</span></td>
      <td><span style="">:</span></td>
      <td><span style="">660</span></td>
    </tr>
    <tr>
      <td><span style="">Date</span></td>
      <td><span style="">:</span></td>
      <td><span style="">15.11.1988</span></td>
    </tr>
    <tr>
      <td><span style="">No</span></td>
      <td><span style="">:</span></td>
      <td><span style="">48961887292</span></td>
    </tr>
    <tr>
      <td><span style="">Phone</span></td>
      <td><span style="">:</span></td>
      <td><span style="">9005312359188</span></td>
    </tr>
     <tr>
      <td><span style="">No</span></td>
      <td><span style="">:</span></td>
      <td><span style="">48961887292</span></td>
    </tr>
    <tr>
      <td><span style="">Phone</span></td>
      <td><span style="">:</span></td>
      <td><span style="">111111111111</span></td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Duncan Thacker
Duncan Thacker

Reputation: 5188

You can do it by looping through each row, finding the one where the first cell contains the word "Phone", and then getting the last cell.

var phoneNumber = false;
$("tbody tr").forEach( function(i, $row ) {
   var $firstCell = $row.find("td:first-child");
   if ( $firstCell.text() === "Phone" ) {
      phoneNumber = $row.find("td:last-child").text();
   }
});

Upvotes: 0

Related Questions