Home > Back-end >  How to Check if second child exsits
How to Check if second child exsits

Time:03-11

I am struggling with how to check if second child exists or not. If it exists then perform certrain functionality:

<table>
  <tr>First tr</tr>
  <tr>First tr</tr>
</table>

CodePudding user response:

You can check the length of the selector results to check the children count. You can then perform your operation or loop through each of them as well.

If you just want to check exactly 2 children, then use === 2 condition. ( code added)

if ($('table tr').length > 1) {
  console.log('second child exists')
}

if ($('table tr').length === 2) {
  console.log('Only two child ')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>First tr</tr>
  <tr>First tr</tr>
</table>

  • Related