I wanna ask that is there any way to insert html content using javascript in such a way like i have a table and inside there is a tbody and inside that i am inserting element using javascript like i am inserting tr and inside that tr i am inserting 5 td and i want that 5 td to have different content and if you try to put all the above stuff in code it will look something like this
JavaScript
x
21
21
1
for(let i = 1; i< 38; i++){
2
3
let swd = {
4
active: data.statewise[i].active,
5
confirmed: data.statewise[i].confirmed,
6
deaths: data.statewise[i].deaths,
7
recovered: data.statewise[i].recovered
8
}
9
10
let swdb = document.getElementById('swdb');
11
12
let swtr = document.createElement('tr');
13
14
swdb.appendChild(swtr);
15
16
for(let j = 1; j<6; j++){
17
let swtd = document.createElement('td');
18
swtr.appendChild(swtd);
19
}
20
}
21
and challenge for me is to insert different content in td inside same tr. And after that final html code should look like this :-
JavaScript
1
8
1
<tr>
2
<td>Custom content 1</td>
3
<td id="active"> Custom content 2</td>
4
<td id="conf">Custom content 3</td>
5
<td id="deaths">Custom content 4</td>
6
<td id="recov">Custom content 5</td>
7
</tr>
8
and after that i will generate more tr like this.
Hope you understand my problem and help me!
Advertisement
Answer
Actually the same example as @b3hr4d but u shouldn’t use .innerHTML
on plain text, choose between .textContent
and .innerText
. Good luck =)
JavaScript
1
16
16
1
const contentList = [
2
{ id: "", text: 'Custom content 1' },
3
{ id: 'active', text: 'Custom content 2' },
4
];
5
6
const tr = document.createElement('tr');
7
contentList.forEach(({ id, text }) => {
8
const td = document.createElement('td');
9
if (id) td.setAttribute('id', id);
10
td.textContent = text;
11
tr.appendChild(td);
12
});
13
14
const root = document.querySelector('#root');
15
root.appendChild(tr);
16
result
JavaScript
1
7
1
<div id="root">
2
<tr>
3
<td>Custom content 1</td>
4
<td id="active">Custom content 2</td>
5
</tr>
6
</div>
7