Reputation: 195
I have this html. I need to .append
certain text based on some conditions:
1) td.name a
contains text which triggers append
2) td.name
and td.quantity
are inside the same row
3) .append
is done only in the same row td.name
and td.quantity
are in.
There are multiple rows. Rows don't have classes and code is dynamically generated - each row may end up on different position in the table. How do I target this
if (jQuery('tbody tr td.name a:contains("text which triggers append")').length > 0) {
jQuery('tbody tr td.quantity').append('<span>text to append</span>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<tbody>
<tr>
<td class="name"><a>text which triggers append</a></td>
<td class="quantity">quantity</td>
</tr>
<tr>
<td class="name"><a>other text</a></td>
<td class="quantity">other quantity</td>
</tr>
</tbody>
Upvotes: 0
Views: 51
Reputation: 4480
Try
jQuery('tbody tr td.name a:contains("text which triggers append")').closest('tr').find('td.quantity').append('<span>text to append</span>');
jQuery('tbody tr td.name a:contains("text which triggers append")').closest('tr').find('td.quantity').append('<span>text to append</span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table border="1">
<tbody>
<tr>
<td class="name"><a>text which triggers append</a></td>
<td class="quantity">quantity</td>
</tr>
<tr>
<td class="name"><a>other text</a></td>
<td class="quantity">other quantity</td>
</tr>
</tbody>
<table>
Upvotes: 1
Reputation: 12181
Here you go with a solution
$('table tbody tr').each(function(){
$(this).find('td.name').each(function(){
if($(this).find('a:contains("text which triggers append")').length > 0){
$(this).siblings('td.quantity').append('<span>text to append</span>');
}
});
});
td {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="name"><a>text which triggers append</a></td>
<td class="quantity">quantity</td>
</tr>
<tr>
<td class="name"><a>other text</a></td>
<td class="quantity">other quantity</td>
</tr>
</tbody>
</table>
As you have mentioned td.name
& td.quantity
are in same row, so I've used jQuery
siblings
to get the td.quantity
.
Hope this will help you.
Upvotes: 0