Jerry Svensson
Jerry Svensson

Reputation: 277

Give parent class if there is no child elements with classes

I have a list of elements and I want to give a class to the parent tr element if the child inside it doesn't have a class assigned to it. Is this possible with jQuery or vanilla JS?

<tr>
 <td class="unfoldedlabel" colspan="6"><a>Accessories</a></td>
</tr>

<tr>
 <td class="foldedlabel" colspan="6"><a>Accessories</a></td>
</tr>

<tr>
 <td><a>Accessories</a></td>
</tr>

Upvotes: 1

Views: 54

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115282

You can use :has() and :not()

$('tr:has(>:not(td[class]))').addClass('class')
.class {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="unfoldedlabel" colspan="6"><a>Accessories</a>
    </td>
  </tr>

  <tr>
    <td class="foldedlabel" colspan="6"><a>Accessories</a>
    </td>
  </tr>

  <tr>
    <td><a>Accessories</a>
    </td>
  </tr>
</table>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

You can use the has() and not() selectors

$('tr').not(':has(td[class])').addClass('no');
tr.no {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="unfoldedlabel" colspan="6"><a>Accessories</a>
    </td>
  </tr>

  <tr>
    <td class="foldedlabel" colspan="6"><a>Accessories</a>
    </td>
  </tr>

  <tr>
    <td><a>Accessories</a>
    </td>
  </tr>
</table>

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

Try this : You can iterate over the trs and check if it has child with specific class and if not then add class to it.

$('tr').each(function(){
  if($(this).children('.childClass').length ==0)
    $(this).addClass('parentClass');
});

Upvotes: 0

Related Questions