Avatar
Avatar

Reputation: 15186

How to select parent from inner element and apply styles to other inner elments of only this parent by .each()?

Well, the question title was not easy to formulate. Maybe an editor can improve it?

Situation: I have 4 tables with the same class name:

<table class="tb">
  <tr><td class="markit">1a</td></tr>
  <tr><td>1b</td></tr>
  <tr><td>1c</td></tr>
</table>
<table class="tb">
  <tr><td>2a</td></tr>
  <tr><td>2b</td></tr>
</table>
<table class="tb">
  <tr><td>3a</td></tr>
  <tr><td>3b</td></tr>
</table>
<table class="tb">
  <tr><td class="markit">4a</td></tr>
  <tr><td>4b</td></tr>
</table>

I want jquery to change the border color of all cells below .markit within the same table, which would be <td>1b</td> and <td>1c</td> and <td>4b</td>.

I tried:

$(".markit").each( function() {
  $('td:nth-child('+($(this).index()+1)+')').css('border-left','4px solid #CCD');
});

But it is changing all td's.

I need to tell jquery to only use the tds of the current parent but I don't know how to set up the selector.

Working code can be seen in this calendar "Ferienkalendar" see today's column.

Upvotes: 1

Views: 502

Answers (3)

Begin Samuel
Begin Samuel

Reputation: 1

$(".markit").each( function(obj) {
    $(this).parent().nextAll().find('td').css('border-left','4px solid #CCD');
});

Upvotes: 0

Pascalz
Pascalz

Reputation: 2378

try like this :

$(".markit").parent().parent().find('td').each(function() {
    $(this).not('.markit').css('border-left','4px solid #CCD');
});

JsFiddle

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Not the prettiest code ever, but try this:

$("table .markit").parent('tr').nextAll().find('td').css('border-left', '4px solid #CCD');

Example fiddle

This code finds all .markit elements, then finds the td elements of all sibling tr of the markit and add the styling to them. I would suggest making that styling a class and using addClass to make maintenance easier in the future. You can also use addBack() to include the original .markit element:

$("table .markit").parent('tr').nextAll().addBack().find('td').addClass('after-markit');

Example including original markit element

Upvotes: 3

Related Questions