I have a table and need to append a <span> to both td:first-child cell and td:first-child cell.
Problems:
There is already exist a
<span>in the first td. How to skip appending if a<span>is already there? (If if statement somehow doesn't work)I wonder why my code doesn't append
<span>in a td:last-childPlease take a look at the second and third rows of the first column, the insert text comes after text in the cell (Jill 2 first-col, Jill 2 first-col). How to move insert text in front?
Please give me a hand. Thanks!
$(document).ready(function() {
$('tr td:first-child').append('<span class="first-col"> first-col</span>');
if ($('tr td:first-child span').length) {
return false
}
$('tr td:last-child').append('<span class="second-col"> second-col</span>')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td><span class="first-col"> first-col</span>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Jill 2</td>
<td>Smith 3</td>
</tr>
<tr>
<td>Jill 3</td>
<td>Smith 3</td>
</tr>
</table>