Issue
I have table with few tr elements and i want to add a new td for the first tr element dynamically in my js.
Table before adding td element.
<table>
<tbody>
<tr>
<td>A</td>
<tr>
<tr>
<td>D</td>
<tr>
<tbody>
<table>
I want a table like this
<table>
<tbody>
<tr>
<td>A</td>
<td>B</td> //Newly addded element
<tr>
<tr>
<td>D</td>
<tr>
<tbody>
<table>
I tried looping through tr elements and adding a new td element using jquery in my js file. Like this :
$('table').each((index,tr)=>{
if(index === 0){
tr.append("<td>B</td>");
}
});
But no lock. [Object object] is being rendered in DOM in the place where I added new td.
Something like this :
Please suggest me solution to add new td in tr's dynamically. Thanks in advance.
Solution
Consider the following example.
$(function() {
function addCell(content, target) {
if(content == undefined){
content = "";
}
return $("<td>").html(content).appendTo(target);
}
addCell("B", $("table tbody tr:eq(0)"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>A</td>
</tr>
<tr>
<td>D</td>
</tr>
</tbody>
</table>
I suspect you will have a button or other opportunities to add content. Creating a small function allows for this to be a bit easier. This function accepts the Content, what you want in the Cell, and the Target.
The last part of it will be to provide a Target. This can be an HTML Element or a jQuery Object. I provided a jQuery Object with the Selector for the TABLE > TBODY > TR (that is equal to Index 0).
You can also use it in a loop:
$("tbody tr").each(function(i, el){
if($("td:eq(0)", el).text() == "A"){
var b = addCell("B", el);
b.addClass("dynamic");
}
});
Answered By - Twisty
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.