Skip to content
Advertisement

Inserting elements using javascript into html

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

for(let i = 1; i< 38; i++){
        
        let swd = {
            active: data.statewise[i].active,
            confirmed: data.statewise[i].confirmed,
            deaths: data.statewise[i].deaths,
            recovered: data.statewise[i].recovered
        }

        let swdb = document.getElementById('swdb');

        let swtr = document.createElement('tr');

        swdb.appendChild(swtr);

        for(let j = 1; j<6; j++){
            let swtd = document.createElement('td');
            swtr.appendChild(swtd);
        }
    }

and challenge for me is to insert different content in td inside same tr. And after that final html code should look like this :-

                    <tr>
                        <td>Custom content 1</td>
                        <td id="active"> Custom content 2</td>
                        <td id="conf">Custom content 3</td>
                        <td id="deaths">Custom content 4</td>
                        <td id="recov">Custom content 5</td>
                    </tr>

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 =)

const contentList = [
  { id: "", text: 'Custom content 1' },
  { id: 'active', text: 'Custom content 2' },
];

const tr = document.createElement('tr');
contentList.forEach(({ id, text }) => {
  const td = document.createElement('td');
  if (id) td.setAttribute('id', id);
  td.textContent = text;
  tr.appendChild(td);
});

const root = document.querySelector('#root');
root.appendChild(tr);

result

<div id="root">
  <tr>
    <td>Custom content 1</td>
    <td id="active">Custom content 2</td>
  </tr>
</div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement