jquery - How to append a string in table cells if and only if that table cell is not empty? -
<table> <tr> <td>aaaa</td> <td>bbbb</td> </tr> <tr> <td></td> <td>ccccc</td> </tr> </table> for above table, how can append string "istring" cell data "aaaa", "bbbb" , "cccc". not empty cell.
$(document).ready(function() { $("table td").each(function() { if($.trim($(this).text()).length > 0) { alert("got td text. appending string"); var text = $.trim($(this).text()); text += "mystring"; $(this).text(text); } }); }); here jsfiddle example.
the $("table td") selector selects each td element of table, , .each() iterator function, execute callback provided argument each element matches selector, td elements of table. inside callback, this refer td element. -
$(this).text().length
portion checking see if text inside td element has length greater zero. if is, you've got td element text. -
var text = $(this).text();
line fetches text td , assigns text variable. next line concatenates specified string variable. finally, -
$(this).text(text);
line assigns concatenated string td element's text.
edit
i've added $.trim() function around string-length checking remove white-space characters. if want consider white-spaces characters, remove it.
Comments
Post a Comment