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.
You don't need a loop for this. There are lots of selectors/methods you can use to target the first td
of the first tr
.
Any of these will work given the HTML structure in your question:
$('table td:first').after('<td>B</td>');
$('<td>B</td>').insertAfter('table td:first');
$('table tr:first').append('<td>B</td>');
$('<td>B</td>').appendTo('table tr:first');
I'm certain there's other ways, but this gives you an idea of the approach to take.
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");
}
});
I try this in pure js
This is my code
HTML:-
<table>
<tbody>
<tr id="myTr">
<td>A</td>
<tr>
<tr>
<td>D</td>
<tr>
<tbody>
<table>
Javascript:-
let myTr = document.getElementById("myTr");
let data = ['B','C'];
data.forEach(item => {
let td = document.createElement("TD");
td.innerHTML = item;
myTr.appendChild(td);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.