Reputation: 3392
I have an HTML table with an inconsistent number of tags per row. For example, one row might have 5 tags and another row might have 2 tags. Is there a convenient way to "pad" the rows with tags containing "N/A" so that there are a consistent number of tags per row?
Quick example:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
I want to be able to add tags to all rows that contain less than 5 tags.
Upvotes: 1
Views: 223
Reputation: 174
If you know the number of columns you need is 'max' then you can try below jquery snippet.
Check each tr and count its child elements . Add td if the total td are less than 'max', then add td.
var max=5;
$('tr').each(function() {
var count = $(this).children().length;
For (int i=count; i <max:i++){
$(this).append("<td>NA</td>");
}
});
If you don't know the value of 'max' then first run a each function to find the max td value. Var Max=0; $('tr').each(function() { var count = $(this).children().length; if (count> max){ Max=count; } });
Upvotes: 0
Reputation: 24405
Here is one method of doing it. First, loop through each row and count how many td elements it has in it. Keep track of the highest number.
var mostTDs = 0;
$('table tr').each(function() {
var thisTDs = $(this).find('td').length;
if(thisTDs > mostTDs)
mostTDs = thisTDs;
});
Then, loop through again and say this time that if the number of tds in this row is less than the largest number, loop and add a td for each extra cell to be added.
$('table tr').each(function() {
var thisTDs = $(this).find('td').length;
for(i = thisTDs; i < mostTDs; i++) {
$('<td/>').html('x').appendTo($(this));
}
});
Upvotes: 1