Search code examples
javascripthtmljqueryuniqueidentifier

How can I identify an element with no class/ID and won't always be the same nth child?


I've got some text displaying in a table (oldschool, I know) and I'm trying to identify that specific <td> element so I can use jQuery to wrap() <a href> tags around it and convert it to a link.

The problem is, none of the <td>'s in the table have unique classes or ID's, and there will always be an unknown amount of <td>'s before the one I want to access, so I don't think I can use nth of child.

The ONLY unique way that <td> is identifiable is the <td> DIRECTLY before it, which will contain some text that will always be the same. Can I use jQuery to find that <td> based on the text inside it, then target the <td> directly after that? Or is there a better way to do this?


Solution

  • You can use jQuery to fetch element that contains specific text and access the next td as required with a single line of jQuery code. This won't thrown an exception in case when there is no next td.

    $(document).ready(function() {
      var yourVal = $('td:contains("2.2")').next('td').text();
      console.log(yourVal);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <table class="table">
      <thead>
        <tr>
          <th>Col 1</th>
          <th>Col 2</th>
          <th>Col 3</th>
          <th>Col 4</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1.1</td>
          <td>1.2</td>
          <td>1.3</td>
          <td>1.4</td>
        </tr>
        <tr>
          <td>2.1</td>
          <td>2.2</td>
          <td>2.3</td>
          <td>2.4</td>
        </tr>
        <tr>
          <td>3.1</td>
          <td>3.2</td>
          <td>3.3</td>
          <td>3.4</td>
        </tr>
      </tbody>
    </table>