gskema
gskema

Reputation: 3211

How to select different cell from the same row in jQuery?

I have this jQuery selector:

'table tbody tr td:first-of-type'

How can I construct a cell selector for the same row from $(this)? I need to check

 $(document).on('click','table tbody tr td:first-of-type',function()
 {
   if ( $('table tbody tr td:nth-child(2)').text() != "" ) // for the same row !!
   //do something
   else
   //do something else
 }

Extra question: should I avoid using CSS3 selectors like nth-child() and use jquery selectors like eq() ?

Upvotes: 2

Views: 2718

Answers (2)

Sunil Kumar
Sunil Kumar

Reputation: 1381

Working Code:

   <html>
        <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(e) {
        if ($('table tbody tr td:nth-child(2)').text() != "" ){ // for the same row
       //do something
        // alert($('table tbody tr td:nth-child(2)').text());
        }else{
       //do something else
       //alert("test");
        }

           });
        </script>

        </head>
        <body>
        <table>
        <tbody>
            <tr>
                <td>itemOne</td>
                <td>itemOneInfo</td>
                <td>Info</td>
            </tr>
            </tbody>
        </table>
        </body>
        </html>

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Just find the closest tr

$(this).closest("tr")

And to select a td, use .find() chained to that:

$(this).closest("tr").find("td") //and whatever criteria you need

Upvotes: 5

Related Questions