Sagive SEO Sagive SEO - 4 months ago 8
Javascript Question

Get the text inside TD by neighbouring TH inner text

i need to get the value of a specific TD which has no ID or Class by the text value of a neighbouring TH using jQuery

Example:

<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>


I want to get the year 1976 (using jQuery) by searching for "Established"

the location of the tr / order isnt always the same.

Possible?

Answer

var year = $("th:contains('Established')").next().text();

console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th>Established</th>
            <td>1976</td>
        </tr>
        <tr>
            <th>Location</th>
            <td>Baltimore, Maryland</td>
        </tr>
    </tbody>
</table>

the above code will work given the string Established will always be in that format (First-uppercase, no spaces, etc).
A more robust solution:

var year = $("th").filter(function(){
  return /^established$/i.test($.trim($(this).text()));
}).nextAll().filter(function() { // If there's more sibling TD...
  // get all that have exactly 4 numbers as text
  return /^\d{4}$/.test($.trim($(this).text()));
}).first().text(); // ...but get the first one's text.

console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th> EstablishEd   </th> <!-- Contains spaces and possible uppercase errors? -->
            <td>1976</td>
        </tr>
        <tr>
            <th>Location</th>
            <td>Baltimore, Maryland</td>
        </tr>
        <tr>
            <th>Workers</th>
            <td>3100</td>
        </tr>
    </tbody>
</table>

https://api.jquery.com/contains-selector/
https://api.jquery.com/next/
https://api.jquery.com/text/