Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<table id="mytable">
    <thead>
        <tr>
            <th>Fruits</th>
           
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Apple</td>
           
        </tr>
        <tr>
            <td>Orange</td>
           
        </tr>
        <tr>
            <td>Mango</td>
           
        </tr>
 <tr>
            <td>Banana</td>
           
        </tr>
 <tr>
            <td>Orange</td>
           
        </tr>
 <tr>
            <td>Apple</td>
           
        </tr>
   <tr>
            <td>Mango</td>
            
        </tr>
    </tbody>
</table>

I want to extract the rows from the table where very first and very last fruit is orange. i.e except first and last two rows in this case.


What I have tried:

i tried looping through array and pusing and popping elements but no luck
Posted
Updated 27-Sep-17 2:35am

1 solution

try

$(document).ready(function () {
          var targetRows = [];
          var rows = $('#mytable tbody tr');
          var tempIndex = [];
          for (var i = 0; i < rows.length; i++)
              if ('Orange' == rows[i].cells[0].innerText)
                  tempIndex.push(i);

          var first = tempIndex[0];
          var last = tempIndex[tempIndex.length - 1];
          for (var i = 0; i < rows.length; i++) {
              if (i >= first && i <= last)
                  targetRows.push(rows[i].cells[0].innerText);
          }
          alert(targetRows.join());
      });


demo: - JSFiddle[^]
 
Share this answer
 
v2
Comments
xpertzgurtej 3-Oct-17 2:51am    
Thanks for your solution. I got idea from this example and completed my actual requirement
Karthik_Mahalingam 3-Oct-17 3:48am    
cool

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900