I have a table of events. Some are ongoing and some have a specific date. The specific date is shown when the event has a date, but I need to add the text 'Ongoing Program' to the empty cells where the date would be.
The snippet I have been working on looks for the class tb2-day
and should add my text to cells that don't have that class on a child element. However, it is adding the text to all cells. How can I fix this?
jQuery(document).ready(function() {
jQuery(".product-type-simple").each(function() {
if ($(this).find('.tb2-day').length) {
jQuery('<p>Ongoing<br>Program</p>').appendTo('.we-first-row');
}
});
});
td {
border: 1px solid #ccc;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table >
<tbody>
<tr >
<td ></td>
<td>content</td>
<td >
<a href="#">info</a>
</td>
</tr>
<tr >
<td ></td>
<td>content</td>
<td >
<a href="#">info</a>
</td>
</tr>
<tr >
<td >
<span >07</span>
<span >June</span>
</td>
<td>content</td>
<td >
<span>
<a href="#">info</a>
</span>
</td>
</tr>
</tbody>
</table>
CodePudding user response:
To do what you require you can create a selector to specifically target the first td
in each row which does not contain a .tb2-day
element:
jQuery($ => {
$(".product-type-simple:not(:has(.tb2-day)) td:nth-child(1)").html('<p>Ongoing<br>Program</p>');
});
td {
border: 1px solid #ccc;
padding: 2px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table >
<tbody>
<tr >
<td ></td>
<td>content</td>
<td >
<a href="#">info</a>
</td>
</tr>
<tr >
<td ></td>
<td>content</td>
<td >
<a href="#">info</a>
</td>
</tr>
<tr >
<td >
<span >07</span>
<span >June</span>
</td>
<td>content</td>
<td >
<span>
<a href="#">info</a>
</span>
</td>
</tr>
</tbody>
</table>
Note that I only amended the padding in CSS to make the UI fit better in to the snippet preview.