betty39johnson
betty39johnson

Reputation: 151

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.

Upvotes: 0

Views: 104

Answers (1)

Rayon
Rayon

Reputation: 36609

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

Upvotes: 6

Related Questions