Got a tricky one where I want to add a class to all the parent <tr>'s of <td>'s which have either a <span> or a <div> element within them. So I have a table with markup as below:
<table>
<tr>
<td>
</td>
<td>
</td>
<td>
<div>
</div>
</td>
<td>
</td>
</tr>
<tr>
<td>
<span></span>
</td>
<td>
</td>
<td>
<div>
</div>
</td>
<td>
</td>
</tr>
</table>
So I want the <td>'s that have either a <span> or <div> to have a class added to them by jQuery...
I can't seem to work out how to loop through all the <td>'s to check their descendant and then add the class to those that have either a <span> or <div> inside... Is this possible?
Thanks for any light you can shed on it! It's driving me mad!
You can check with .has() if tr has div or span as a descendant:
$('table tr').has('div,span').addClass('someClass');
Check the below snippet:
$('table tr').has('div,span').addClass('someClass');
.someClass {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>td 1</td>
<td>td 2</td>
<td>
<div>div</div>
</td>
<td>td 3</td>
</tr>
<tr>
<td>td 1</td>
<td>td 2</td>
<td>td 3</td>
<td>td 4</td>
</tr>
<tr>
<td><span>span</span>
</td>
<td>td 1</td>
<td>
<div>div</div>
</td>
<td>td 2</td>
</tr>
<tr>
<td>td 1</td>
<td>td 2</td>
<td>td 3</td>
<td>td 4</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With