Home > database >  Finding text of nested td next to another td in jquery
Finding text of nested td next to another td in jquery

Time:07-25

I have the following html table. In each row there is always a td with the label Id num: inside a table nested inside the first table.

<table id="a_known_id">
    <tr> 
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>

    <tr>
        <td>One</td>
        <td>Two
            <table>
                <tr><td>Detail 1</td><td>Detail 1b</td></tr>
                <tr><td>Id num:</td><td>Some Id</td><tr>
            </table>
        </td>
        <td>Three
            <table>
                <tr><td>Detail 2</td><td>Detail 2b</td></tr>
                <tr><td>T</td><td>Some T</td></tr>
            </table>
        </td>
    </tr>

    <tr>
        <td>Four</td>
        <td>Five
            <table>
                <tr><td>Detail 3</td><td>Detail 3b</td></tr>
                <tr><td>Id num:</td><td>Some other Id</td><tr>
            </table>
        </td>
        <td>Six
            <table>
                <tr><td>Detail 4</td><td>Detail 4b</td></tr>
                <tr><td>R</td><td>Some R</td></tr>
            </table>
        </td>
    </tr>
    <!-- same pattern -->
</table>

I would like to get the text content of the td next to the td with the text Id num:

I tried this

$("table[id=a_known_id] tr:not(:first) td:contains('Id num:')").each(function() {
            
            var text = $(this).next().text();
});

but it doesnt quite work

CodePudding user response:

Try this

$("table#a_known_id table tr:not(:first-child) td:contains('Id num:')   td").each(function() {
    var text = $(this).text();
    console.log(text)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="a_known_id">
    <tr> 
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>

    <tr>
        <td>One</td>
        <td>Two
            <table>
                <tr><td>Detail 1</td><td>Detail 1b</td></tr>
                <tr><td>Id num:</td><td>Some Id</td><tr>
            </table>
        </td>
        <td>Three
            <table>
                <tr><td>Detail 2</td><td>Detail 2b</td></tr>
                <tr><td>T</td><td>Some T</td></tr>
            </table>
        </td>
    </tr>

    <tr>
        <td>Four</td>
        <td>Five
            <table>
                <tr><td>Detail 3</td><td>Detail 3b</td></tr>
                <tr><td>Id num:</td><td>Some other Id</td><tr>
            </table>
        </td>
        <td>Six
            <table>
                <tr><td>Detail 4</td><td>Detail 4b</td></tr>
                <tr><td>R</td><td>Some R</td></tr>
            </table>
        </td>
    </tr>
    <!-- same pattern -->
</table>

  • Related