Search code examples
javascripthtml-tablequeryselector

How to add an element inside another element which was added in the same function in JavaScript?


I am making a website project and I'm trying to make a function that will add new rows (<tr>) into an already existing empty table (<table>) and create cells (<td>) inside these rows containing informantion from a .json file. The first row contains certain dates and the first cell in every other row contains names of people.

Everything works just fine except for one thing. I want to add cells that fill the rest of the table. I will put some info about the people's schedules in those cells. I wanted to do it in the same function so that everything is added together right away but for some reason this specific part doesn't work.

Here's an example of the JavaScript code:

for(let x in namesArray){
      let tr = document.createElement('tr')
      tr.className = "plan";
      tr.innerHTML= "<th class='name'>"+namesArray[x]+"</th>";
      document.querySelector('tbody').appendChild(tr);
};
     
for(let i = 0; i < amountOfDates; i++)
{
      document.querySelectorAll(".plan").forEach(function(y){
      let td = document.createElement('td');
      td.className = "class_plan";
      y.appendChild(td);
      });


document.querySelectorAll(".class_plan").forEach(function(x){ 
      let span = document.createElement('span');
      span.className = "description";
      x.appendChild(span);
});

When I run the code the table works fine. The names are displayed properly, but it seems that the rest of the code doesn't work.

From my understanding, the code doesn't register any elements with the class ".plan" which is why the other cells are not displayed in the table. I'm not sure how to overcome this problem though.

This is how the table should've looked like:

Date 1 Date 2
Name 1 Cell 1 Cell 2
Name 2 Cell 3 Cell 4

But instead the cells don't show up at all.

I've tried separating this code into two different functions, but it still doesn't work.


Solution

  • You can try this

    for(let x in namesArray){
          let tr = document.createElement('tr')
          tr.className = "plan";
          tr.innerHTML= "<th class='name'>"+namesArray[x]+"</th>";
    
          for(let i = 0; i < amountOfDates; i++)
          {
              let td = document.createElement('td');
              td.className = "class_plan";
              let span = document.createElement('span');
              span.className = "description";
              td.appendChild(span);
              tr.appendChild(td);
          }
          document.querySelector('tbody').appendChild(tr);
    
    };