简体   繁体   中英

javascript add class to next 7 elements

I was wondering how to add class to next 7 elements of parent using javascript? I want to highlight next six elements after choice

  <table>
   <tr>
     <td>list item 1</td>
     <td>list item 2</td>
     <td>list item 3</td>
     <td>list item 4</td>
     <td>list item 5</td>
   </tr>
   <tr>
     <td>list item 6</td>
     <td>list item 7</td>
     <td>list item 8</td>
     <td>list item 9</td>
     <td>list item 10</td>
   </tr>
   </table>

I read about :eq, :lt(index) selectors, but it doesn't work. Thanks in advance.

You can use :lt selector which will select matched elements with index less than specified number(Index starts from 0)

In this example, 0-6 td elements will be selected. In case you want to mention start index, use :gt with the start index

Try this:

 $('table td:lt(7):gt(2)').css('color', 'red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr> <td>list item 1</td> <td>list item 2</td> <td>list item 3</td> <td>list item 4</td> <td>list item 5</td> </tr> <tr> <td>list item 6</td> <td>list item 7</td> <td>list item 8</td> <td>list item 9</td> <td>list item 10</td> </tr> </table> 

Note: If you combine lt and gt then it will work in order in which they are specified. In above example, selector will select td elements less than index 7 and then filter them out with index greater than 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM